If we want to assign a value to a variable in a Dynamic Query, then it throws an error. Below is an example:
1
2
3
| DECLARE @V_SQL VARCHAR(MAX), @Row_Cnt_Stg INTSET @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:
1
2
| Msg 137, Level 15, State 1, Line 1Must 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 :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
| -- Declaring VariablesDECLARE @V_SQL VARCHAR(MAX), @Row_Cnt_Stg INT, @TableName VARCHAR(20), @DatabaseName VARCHAR(20)-- Assigning the values to the variablesSET @DatabaseName = DB_NAME(DB_ID())SET @TableName = 'TEST_EMP'-- Assigning the Dynamic Queries using the variablesSET @SQL = 'SELECT @Row_Cnt_Stg =COUNT(*) FROM ' + @DATABASENAME + '.dbo.' + @TableNamePRINT(@SQL)-- Executing the Dynamic queryEXEC 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 QuerySELECT @Row_Cnt_Stg |
No comments:
Post a Comment