执行如下SQL

SQL server 动态SQL对变量讲行赋值declare @t int
SQL server 动态SQL对变量讲行赋值
exec('set @t=1')
SQL server 动态SQL对变量讲行赋值
print(@t)

报如下错误!
服务器: 消息 137,级别 15,状态 2,行 1
必须声明变量
'@t'

 

 实际就是变量与动态语句不能共享,

那么换成这样就行,

SQL server 动态SQL对变量讲行赋值declare @t int
SQL server 动态SQL对变量讲行赋值
set @t=1
SQL server 动态SQL对变量讲行赋值
print(@t)


SQL server 动态SQL对变量讲行赋值exec('declare @t int;
SQL server 动态SQL对变量讲行赋值set @t=1;
SQL server 动态SQL对变量讲行赋值print(@t)
')


但是有时候你一定要,变量与动态SQL结合起来。
比如,你在存储过程中定义一个输出参数,◎COUNT int output
而你在获得这个值的最好的方法就是动态SQL,那么有什么好的方式吗?
那就要用到系统存储过程,sp_executesql

SQL server 动态SQL对变量讲行赋值 
SQL server 动态SQL对变量讲行赋值         
declare @sql2 nvarchar(500)
SQL server 动态SQL对变量讲行赋值           
set @sql2 = 'select @COUNT = count(distinct('+@groupby+')) from TG_ENTRY where '+@sqlWhere
SQL server 动态SQL对变量讲行赋值    
execute sp_executesql 
SQL server 动态SQL对变量讲行赋值          
@sql2,
SQL server 动态SQL对变量讲行赋值          N
'@COUNT int output',
SQL server 动态SQL对变量讲行赋值          
@TOTAL_COUNT output

相关文章:

  • 2022-12-23
  • 2022-02-19
  • 2022-12-23
  • 2021-10-17
  • 2021-05-19
  • 2022-12-23
  • 2022-01-26
  • 2022-12-23
猜你喜欢
  • 2021-05-21
  • 2021-09-29
  • 2022-12-23
  • 2021-08-16
  • 2021-06-22
  • 2022-12-23
相关资源
相似解决方案