当前位置:Gxlcms > 数据库问题 > [转]使用exec和sp_executesql动态执行SQL语句

[转]使用exec和sp_executesql动态执行SQL语句

时间:2021-07-01 10:21:17 帮助过:24人阅读

(select * from Student)

exec sp_executesql Nselect * from Student--此处一定要加上N,否则会报错

 

2.带参数的SQL语句

declare @sql nvarchar(1000)

declare @userId varchar(100)

set @userId=0001

set @sql=select * from Student where UserID=‘‘‘+@userId+‘‘‘‘

exec(@sql)

 

declare @sql nvarchar(1000)

declare @userId varchar(100)

set @userId=0001

set @sql=Nselect * 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语句

 1 create procedure [dbo].[sp_GetNameByUserId]
 2 (
 3     @userId varchar(100),
 4     @userName varchar(100) output
 5 )
 6 as
 7 begin
 8 
 9     declare @sql nvarchar(1000)
10     set @sql=Nselect @userName=UserName from Student where UserId=@userId
11     exec sp_executesql @sql,N@userId varchar(100),@userName varchar(100) output,@userId,@userName output
12     select @userName
13 
14 end

 

 

 

原文链接

 


---------------------
作者:PowerCoder
来源:CNBLOGS
原文:https://www.cnblogs.com/OpenCoder/p/10771382.html
版权声明:本文为作者原创文章,转载请附上博文链接!
内容解析By:CSDN,CNBLOG博客文章一键转载插件

[转]使用exec和sp_executesql动态执行SQL语句

标签:exec   插件   coder   提高   cut   csdn   相对   pts   sql   

人气教程排行