前言
一、使用exec
1.用拼接方法
二、使用sp_executesql
1.用拼接方法
2.传参的方法
总结
前言
例如:列表查询条件不固定,根据前端传过来的参数,这时需要根据查询条件后台动态生成SQL语句
一、使用exec
exec适用于字符串拼接的方式,如果参数是非nvarchar类型需要转化成此类型做拼接
1.用拼接方法
例如:我要找出某位作者在合适价格的书一个月出版书
代码如下(示例):
declare @AuthorName nvarchar(20)
declare @Price int
declare @PubTime date
declare @sql  nvarchar(max); 
set @sql='select * from book where 1=1 ';
--找出某位作者的书
set @AuthorName='小王'
if(ISNULL(@AuthorName,'')<>'')		
begin
set @sql=@sql+ 'and AuthorName='''+@AuthorName+'''';
end
--找出符合价格的书
set @Price=60;
if(ISNULL(@Price,'')<>'')		
begin
set @sql=@sql+ 'and Price='''++CAST(@Price as nvarchar)+''''
end
set @PubTime='2023-04-01'
--找某个月的出版的书
if(ISNULL(@PubTime,'')<>'')		
begin
set @sql=@sql+ 'and PubTime>=DATEADD(MONTH, DATEDIFF(MONTH, 0,'''+cast(@PubTime as nvarchar)+'''), 0)' --某月的第一天
set @sql=@sql+'and  PubTime<=DATEADD(MONTH, DATEDIFF(MONTH, -1,'''+cast(@PubTime as nvarchar)+'''), -1)' --某月的最后一天
end
exec(@sql)
print  @sql
 返回结果

二、使用sp_executesql
比exec更加灵活,及支持字符串拼接的方式,并且 支持参数化
1.用拼接方法
获取小王出版的所有的书
代码如下(示例):
    declare @sql nvarchar(300)
    declare @AuthorName nvarchar(500)
    set @AuthorName='小王'
    set @sql = 'SELECT max(price) FROM book where  AuthorName='''+@AuthorName+''''
    --方式1
    exec sp_executesql @sql
    --方式二
    exec(@sql)
    print @sql
返回结果

2.传参的方法
比如 输出小王共计出版了多少本书,并用一个变量接收
代码如下(示例):
    declare @sql nvarchar(300)
    declare @AuthorName nvarchar(500)
	declare @Num int;
    set @AuthorName='小王'
    set @sql = 'SELECT @Num=count(1) FROM book where  AuthorName=@AuthorName'
    exec sp_executesql @sql,N'@AuthorName nvarchar(300),@Num int out', @AuthorName, @Num  out
    
	--exec(@sql)
	select @Num as 数量
	PRINT @Num 
返回结果

三、应用上
支持在存储过程里使用,不支持在FUNCTIO函数的使用
在表值函数使用exec、sp_executesql
代码如下(示例):
CREATE FUNCTION fntest
(
@AuthorName nvarchar(500)
)
RETURNS 
@t TABLE 
(
	   [Id] int 
      ,[AuthorName] nvarchar
      ,[Price] float
      ,[PubTime] datetime
      ,[Title]  nvarchar
)
AS
BEGIN
	
    declare @sql nvarchar(300)
    set @sql = 'insert into @t SELECT * FROM book where  AuthorName='''+@AuthorName+''''
    --方式1
	insert into @t
    exec sp_executesql @sql
    --方式二
    exec(@sql)
    print @sql
	
	RETURN 
END返回结果

总结
exec 只适用于拼接的方式,而sp_executesql更加灵活,不仅用拼接方式,而且支持参数化
exec、sp_executesql 动态拼接的方式 适用在存储过程中使用,不支持在表值函数、标量函数中使用



















