动态SQL语句,动态SQL语句
【 tulaoshi.com - SQLServer 】
1:普通SQL语句可以用Exec执行
eg: Select * from tableName
Exec('select * from tableName')
sp_executesql N'select * from tableName' -- 请注意字符串前一定要加N
2:字段名,表名,数据库名之类作为变量时,必须用动态SQL
eg:
declare @fname varchar(20)
set @fname = '[name]'
Select @fname from sysobjects -- 错误
Exec('select ' + @fname + ' from sysobjects') -- 请注意 加号前后的 单引号的边上要加空格
exec sp_executesql N' select ' + @fname + ' from sysobjects'
当然将字符串改成变量的形式也可
declare @s varchar(1000)
set @s = 'select ' + @fname + ' from sysobjects'
Exec(@s) -- 成功
exec sp_executesql @s -- 此句会报错
declare @s Nvarchar(1000) -- 注意此处改为nvarchar(1000)
set @s = 'select ' + @fname + ' from sysobjects'
Exec(@s) -- 成功
exec sp_executesql @s -- 此句正确,
3: 输出参数
eg:
declare @num,
@sqls
set @sqls='select count(*) from ' + @servername + '.a.dbo.b'
exec(@sqls)
我如何能将exec执行的结果存入变量@num中
declare @num int,
@sqls nvarchar(4000)
set @sqls='select @a=count(*) from '+@servername+'.a.dbo.b'
exec sp_executesql @sqls,N'@a int output',@num output
select @num
来源:http://www.tulaoshi.com/n/20160129/1499508.html