devxlogo

Selecting into a Variable Using Dynamic SQL

Selecting into a Variable Using Dynamic SQL

Asking how to select into a variable using dynamic SQL is a frequent question on newsgroups because SQL Server will not let you select into a variable using the EXEC() function. To get around this, you can create a temporary table and build the SQL dynamically to insert a row into it with the value you want to SELECT into a variable. You can then EXEC() the SQL and SELECT the value into the variable from the temporary table.

For example, suppose you wanted to create a stored procedure that returned the number of rows ina table:

 DROP PROC sp_countGOCREATE PROC sp_count@vcTable sysnameASSET NOCOUNT ONDECLARE @intCount int     , @vcSQL varchar(255)SELECT    @vcSQL = " SELECT @intCount = COUNT(*) FROM " + @vcTableEXEC      (@vcSQL)IF @@ERROR = 0     RETURN @intCountELSE     RETURN -1GO

You get:

 Msg 137, Level 15, State 1Must declare variable '@intCount'.NumRows------------1

Change this to:

 DROP PROC sp_countGOCREATE PROC sp_count@vcTable sysnameASSET NOCOUNT ONCREATE TABLE #ctr( NumRows int )DECLARE @intCount int     , @vcSQL varchar(255)SELECT    @vcSQL = " INSERT #ctr SELECT COUNT(*) FROM " + @vcTableEXEC      (@vcSQL)IF @@ERROR = 0BEGIN     SELECT    @intCount = NumRows     FROM #ctr     DROP TABLE #ctr     RETURN @intCountENDELSEBEGIN     DROP TABLE #ctr     RETURN -1ENDGODECLARE @intCount intEXEC      @intCount = sp_count sysusersSELECT    @intCount NumRows

And you get:

 NumRows-----------105

See also  Essential Measures for Safeguarding Your Digital Data
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist