Vous êtes sur la page 1sur 3

Aqu se mostrarn algunas buenas prcticas de SQL

1 - siempre especificar las columnas en un select


(Al especificar las columnas hay menos transporte de informacin del medio fsico a la memoria
para manejo de los datos)
2 - Usar variables tipo tabla en lugar de tablas temporales
(Las variables tipo tabla residen en memoria casi siempre a menos que sean muy grandes, y las
tablas temporales residen en tempdb que resulta en una intercomunicacin de bases de datos)
3 - evitar el uso de cursores, si se puede cambiarlos por subconsultas, o mejor an utilizar joins
(sql genera un plan de ejecucin por cada ciclo dentro de un cursos, si se hace por subconsultas o
joins, sql genera la forma optima de solucionar los requerimientos del query)
4 - evitar la llamada de funciones, Stores Procedures dentro de selects
(Igual que los cursores, (procedural sql aproximation), decrementan el rendimiento, porque se
crea un plan de ejecucin para cada rengln que genere la consulta principal)
5 cambiar de cursor approach a table variable approach
CURSOR:
--Declare the Table variable
DECLARE @Elements TABLE
(
ProductName VARCHAR(300) --The string value
)
--Populate the TABLE variable using some logic
INSERT INTO @Elements SELECT Name FROM dbo.Products
--A variable to hold the currently selected value from the table
DECLARE @CurrentValue varchar(300);
--Decalre Cursor for itrate @Elements
DECLARE CursorElements FAST_FORWARD CURSOR FOR
SELECT * FROM @Elements
OPEN CursorElements
FETCH CursorElements INTO @CurrentValue
WHILE (@@FETCH_STATUS = 0)
BEGIN
--Process the current value
print @CurrentValue
--Next Value stored in @CurrentValue
FETCH CursorElements INTO @CurrentValue
END
--Close Cursor
CLOSE CursorElements
--Free Resources
DEALLOCATE CursorElements

TABLE VARIABLE:

--Declare the Table variable


DECLARE @Elements TABLE
(
Number INT IDENTITY(1,1), --Auto incrementing Identity column
ProductName VARCHAR(300) --The string value
)
--Decalre a variable to remember the position of the current delimiter
DECLARE @N INT
--Decalre a variable to remember the number of rows in the table
DECLARE @Count INT
--Populate the TABLE variable using some logic
INSERT INTO @Elements SELECT Name FROM dbo.Products
--Initialize the looper variable
SET @N = 1
--Determine the number of rows in the Table
SELECT @Count=max(Number) from @Elements
--A variable to hold the currently selected value from the table
DECLARE @CurrentValue varchar(300);
--Loop through until all row processing is done
WHILE @N <= @Count

BEGIN
--Load current value from the Table
SELECT @CurrentValue = ProductName FROM @Elements WHERE Number = @N
--Process the current value
print @CurrentValue
--Increment loop counter
SET @N = @N + 1;
END

Vous aimerez peut-être aussi