SQL Server提供了2个用于执行动态构造的代码字符串命令,分别为exec和sp_executesql.
Exec 有两种用法:一种是执行一个存储过程。
表结构及测试数据如下:
create table [User]
(
userid int identity primary key,
userName nvarchar(8),
pwd nvarchar(18),
city nvarchar(20),
[type] bit,
createtime datetime default getdate()
)
insert into [User] (userName,pwd,city,[type])
select 'a','aa','beijing',1 union
select 'b','bb','shanghai',1 union
select 'c','cc','tianjin',0 union
select 'd','dd','tianjin',0
存储过程如下:
create procedure pro_GetUserbyCity
@City nvarchar(20)
as
begin
select * from [user] where city=@City
end
执行存储过程:
exec pro_GetUserbyCity 'tianjin'
另一种用来执行字符串:
Exec(string)必须用括号括起来
declare @city nvarchar(20), @sql nvarchar(50)
set @city='tianjin'
--set @sql='select * from [user] where city='''+CONVERT(nvarchar,@city)+'''' --有SQL注入危险
set @sql='select * from [user] where city='+QUOTENAME(@city,'''')
print @sql
exec(@sql)
执行结果同上
sp_executesql:可以提供输入参数和输出参数:此外sql 语句必须是unicode(nvarchar)类型的
用法:
Exec sp_executesql
@sql,--要执行的语句
@params ,--语句当中的参数
@assignment—给参数赋值
declare @city nvarchar(20), @sql nvarchar(50)
set @city='tianjin'
set @sql=N'select * from [user] where city=@c'
print @sql
exec sP_executesql @sql,N'@c as nvarchar(20)',@city
执行结果同上
带返回值的
declare @city nvarchar(20), @sql nvarchar(100),@num int
set @city='tianjin'
set @sql=N'select @n=count(*) from [user] where city=@c;select @n;'
print @sql
exec sP_executesql @sql,N'@c as nvarchar(20),@n as int output',@city,@num
执行结果如下