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
Advertisements
  • Recent Posts

    • 489,104 hits
  • Join 37 other followers

  • Archives

  • Categories

  • August 2019
    M T W T F S S
    « Feb    
     1234
    567891011
    12131415161718
    19202122232425
    262728293031  
  • Advertisements