Friday, September 25, 2015

Cursors are ghetto. Just select directly to temp tables and table variables.

Note the difference between the two in T-SQL here and the how-to explaination here. For a table variable you will approach it like so:

DECLARE @Widgets TABLE
(
   WidgetId int NOT NULL,
   WidgetName NVARCHAR(50) NOT NULL
)
INSERT INTO @Widgets
SELECT WidgetId, WidgetName FROM dbo.Widget
SELECT * FROM @Widgets

 
 

A temp table can be approached in an easier manner:

IF OBJECT_ID('tempdb..#Widgets') IS NOT NULL DROP TABLE #Widgets
SELECT WidgetId, WidgetName INTO #Widgets FROM dbo.Widget
SELECT * FROM #Widgets

No comments:

Post a Comment