sp_executesql 条件始终为真
sp_executesql with always true condition
我一直在 sql-server 中使用动态查询,例如:
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'.
我的问题是如何使上述查询与 sp_executesql
一起使用,其中参数 @condition 可以是条件或空白 (' '),我做错了什么。
当你在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
我一直在 sql-server 中使用动态查询,例如:
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'.
我的问题是如何使上述查询与 sp_executesql
一起使用,其中参数 @condition 可以是条件或空白 (' '),我做错了什么。
当你在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