我试图根据条件构建动态顺序的动态查询。但由于某种原因,即席查询工作正常,但使用 withsp_executesql返回空值相同。如有任何问题,请提出建议。以下是示例数据。7 z; ^1 m9 d, q" k0 W
create table resource_statistics (id int ,parameter_name varchar(255),parameter_value INT) INSERT INTO resource_statistics values (1,'temparature INSERT INTO resource_statistics values (2,'humidity INSERT INTO resource_statistics values (3,'wind5) INSERT INTO resource_statistics values (4,'wind INSERT INTO resource_statistics values (5,'humidity ,90)INSERT INTO resource_statistics values (6,'humidity 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=0select parameter_name,parameter_valuefromresource_statisticsORDER BY CASE WHEN @test = 'parameter_name' THEN CASE @tvalue when '1' THEN parameter_name ELSE NULL END END DESC尝试将上述查询转换为动态 SQL,但执行结果是空的。 , r& t- m6 y1 x( T+ V/ X2 i7 f; ~declare @test varchar(255)='parameter_name',@tvalue INT=0,@sqlquery NVARCHAR(MAX)SET @sqlquery='select parameter_name,parameter_valuefromresource_statisticsORDER BY ' CASE WHEN @test ='parameter_name' THEN CASE @tvalue when '1' THEN 'parameter_name' ELSE NULL END END ' DESC'select @sqlqueryexecute sp_executesql @sqlquery 7 ^ r( V$ V) R% j解决方案: 5 ^- f I. N7 q0 x6 E; Z9 h$ ]
不要使用else NULL.只需使用else '': p* _% Z+ I5 ~. E) p* ydeclare @test varchar(255) = 'parameter_name @tvalue INT = 0, @sqlquery NVARCHAR(MAX);SET @sqlquery = N'select parameter_name,parameter_valuefrom resource_statisticsorder by (case when @test = 'parameter_name' and @tvalue = then 'parameter_name DESC' else '' end)select @sqlquery;execute sp_executesql @sqlquery;你可能已经知道,将参数合并到这样的 SQL 查询中既有意外语法错误的风险,也有 SQL 注入的风险。但是,您得到的NULL因为如果任何操作数为 , 返回。NULLNULL