研究了一下SQL Server中动态SQL的用法,写惯了Oracle,对于SQL Server还有些不习惯
create table test_with(
pid int,
parentid int,
name varchar(60)
)
declare @pid int = '99',@name nvarchar(60) = 'ABCD'
declare @parentid int = 2
declare @sql varchar(3000)
set @sql = 'insert into test_with values('+CAST(@pid as varCHAR(10))+','+CAST(@pid as varCHAR(10))+',"'+CAST(@name as varCHAR(10))+'")'
print @sql
exec (@sql)
declare @dynamic_sql nvarchar(4000)
execute sp_executesql @dynamic_sql ,N'@pid int,@parentid int ,@name nvarchar(60)',@pid,@parentid,@name --绑定变量
另一个写法:
declare @sql nvarchar(4000)
declare @pid int
declare @dt datetime
set @pid = 99
set @dt = GETDATE() + 2
set @sql = 'select @dt as dt, pid, name from test_with where pid = @pid'
execute sp_executesql @sql, N'@dt datetime, @pid int', @dt, @pid
需要注意的是,在SQL SERVER 2008 R2里,@sql必须声明为nvarchar
而且参数声明部分也应声明为unicode编码
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/8520577/viewspace-1062174/,如需转载,请注明出处,否则将追究法律责任。