我一直在SQL服务器中使用动态查询,例如:
declare @sql nvarchar (1000),@condition nvarchar(100)='';
set @sql=N'select * from tablename where (0=0)'+@condition+'';
exec(@sql)
通过这种方式,无论@condition是否有任何价值,我都能够得到我的结果。但是我知道sp_executesql
比exec
更好,因为它促进了查询计划的重用。
因此,我尝试使用"sp_executesql,
set @sql =N'select * from dbo.testclient where (0=0) @condition'
exec sp_executesql @sql,N'@condition nvarchar(100)',@condition
但它失败并出现错误
Incorrect syntax near '@condition'.
我的问题是我如何使上述查询适用于参数@condition可以是条件或空白 (' '( 的sp_executesql
以及我做错了什么。
当您在sp_executesql中使用诸如@condition之类的变量时,它不会简单地将 sql 字符串中的变量替换为变量的内容。
发生的情况是变量绑定到提供的值,并且 sql 语句保持不变。
这一切都意味着,如果要利用查询计划重用,则需要创建一个使用变量的完整 sql 语句。
例如:
SET @byIDsql = 'select * from tableName where (0=0) and Id = @Id'
SET @byNameSQL = 'select * from tableName where (0=0) and FirstName = @FirstName'
然后,可以使用 sp_executesql 提供 @id 的值,并@firstName获取查询计划重用。
exec sp_executesql @byIDsql, N'@ID INT', 15
测试代码,
DECLARE @Sql nvarchar(MAX)='',
@paramlist nvarchar(4000),
@id int=3
set @paramlist = N' @id1 int'
set @Sql='select * from test where id=@id1'
exec sp_executesql @Sql,@paramlist,@id
select @Sql