declare @sql nvarchar(2000)
declare @cou int
declare @id varchar(20)
set @id=’1′
set @sql=’select @count=count(*) from emp where id=@id’
exec sp_executesql @sql, N’@count int out,@id varchar(20)’, @cou out
,@id
print @cou
1..普通SQL语句
(1)exec(‘select * from Student’)
(2)exec sp_executesql N’select * from Student’–此处一定要加上N,否则会报错
2.带参数的SQL语句
(1)declare @sql nvarchar(1000)
declare @userId varchar(100)
set @userId=’0001′
set @sql=’select * from Student where UserID=”’+@userId+””
exec(@sql)
(2)declare @sql nvarchar(1000)
declare @userId varchar(100)
set @userId=’0001′
set @sql=N’select * from Student where UserID=@userId’
exec sp_executesql @sql,N’@userId varchar(100)’,@userId
从这个例子中可以看出使用sp_executesql可以直接将参数写在sql语句中,而exec需要使用拼接的方式,这在一定程度上可以防止SQL注入,因此sp_executesql拥有更高的安全性。另外需要注意的是,存储sql语句的变量必须声明为nvarchar类型的。
(3)带输出参数的SQL语句
create procedure sp_GetNameByUserId
(
@userId varchar(100),
@userName varchar(100) output
)
as
declare @sql nvarchar(1000)
set @sql=N’select @userName=UserName from Student where UserId=@userId’
exec sp_executesql N’@userId varchar(100),@userName varchar(100) output’,@userId,@userName output
select @userName