Assigning Values dynamically in SQL Server

If we want to assign a value to a variable in a Dynamic Query, then it throws an error. Below is an example:

DECLARE @V_SQL VARCHAR(MAX), @Row_Cnt_Stg INT
SET @V_SQL ='SELECT @ROW_CNT_STG= COUNT(*) FROM TEST.dbo.TEST_EMP'
EXEC(@V_SQL)

If we execute above query, then the below error is raised:

Msg 137, Level 15, State 1, Line 1
Must declare the scalar variable "@Row_Cnt_Stg".

Even though we have declared the variable @Row_Cnt_Stg as Integer datatype, still SQL will raise error as above. In order to overcome this error use the below statements. When we execute the below query it will assign the value to the variable :

-- Declaring Variables
DECLARE @V_SQL VARCHAR(MAX), @Row_Cnt_Stg INT,  @TableName  VARCHAR(20), @DatabaseName  VARCHAR(20)

-- Assigning the values to the variables
SET @DatabaseName = DB_NAME(DB_ID())
SET @TableName = 'TEST_EMP'

-- Assigning the Dynamic Queries using the variables
SET @SQL = 'SELECT @Row_Cnt_Stg =COUNT(*) FROM ' + @DATABASENAME + '.dbo.' + @TableName
PRINT(@SQL)

-- Executing the Dynamic query
EXEC SP_EXECUTESQL @V_SQL, N'@Row_Cnt_Stg INT OUTPUT', @Row_Cnt_Stg OUTPUT

-- Selecting the values from the variable that is assigned in the Dynamic Query
SELECT @Row_Cnt_Stg
Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: