我正在尝试按条件构建动态顺序的动态查询。但出于某种原因,即席查询工作正常,但使用 withsp_executesql返回空值相同。如果查询有任何问题,请提出建议。下面是示例数据。
withsp_executesql
create table resource_statistics (id int , parameter_name varchar(255), parameter_value INT) INSERT INTO resource_statistics values (1,'temparature',28); INSERT INTO resource_statistics values (2,'humidity',67) INSERT INTO resource_statistics values (3,'wind',5) INSERT INTO resource_statistics values (4,'wind',28) INSERT INTO resource_statistics values (5,'humidity',90) INSERT INTO resource_statistics values (6,'humidity',45) INSERT INTO resource_statistics values (7,'temparature',38) Below query returns the correct data set if ! switch the @tvalue with 0 and 1. declare @test varchar(255)='parameter_name', @tvalue INT=0 select parameter_name,parameter_value from resource_statistics ORDER BY CASE WHEN @test = 'parameter_name' THEN CASE @tvalue when '1' THEN parameter_name ELSE NULL END END DESC
尝试将上述查询转换为动态 SQL,但执行结果为空。
declare @test varchar(255)='parameter_name', @tvalue INT=0,@sqlquery NVARCHAR(MAX) SET @sqlquery=' select parameter_name,parameter_value from resource_statistics ORDER BY ' + CASE WHEN @test ='parameter_name' THEN CASE @tvalue when '1' THEN 'parameter_name' ELSE NULL END END +' DESC' select @sqlquery execute sp_executesql @sqlquery
不要使用else NULL.只需使用else '':
else NULL.
else ''
declare @test varchar(255) = 'parameter_name', @tvalue INT = 0, @sqlquery NVARCHAR(MAX); SET @sqlquery = N' select parameter_name, parameter_value from resource_statistics order by ' + (case when @test = 'parameter_name' and @tvalue = '1' then 'parameter_name' + ' DESC' else '' end) select @sqlquery; execute sp_executesql @sqlquery;
您可能已经知道,将参数合并到这样的 SQL 查询中既存在意外语法错误的风险,也存在 SQL 注入的风险。但是,您得到的NULL是因为如果任一操作数为 ,则+返回。NULLNULL