简体   繁体   English

存储过程不适用于动态 where 子句

[英]Stored procedure isn't working with a dynamic where clause

I have created a stored procedure that has a few select statements and the last where the condition is inside a @command.我创建了一个存储过程,其中包含一些 select 语句,最后一个条件位于 @command 中。 Since I am running this in C#.因为我在 C# 中运行它。

CREATE PROCEDURE [dbo].[SearchList]  
    @command varchar(2000) 
AS
BEGIN
    SELECT * 
    FROM XYZ + CONVERT(varchar(2000), @command)
END

I keep getting an error我不断收到错误

Conversion failed when converting the varchar value ' ORDER BY ID DESC' to data type int将 varchar 值“ORDER BY ID DESC”转换为数据类型 int 时转换失败

DECLARE @return_value int

EXEC    @return_value = [dbo].[SearchList]
        @command = N' ORDER BY Id DESC'

SELECT  'Return Value' = @return_value
GO

The output returns a list which I then bind it in a grid. output 返回一个列表,然后我将其绑定到网格中。

You can try below solution您可以尝试以下解决方案

CREATE PROCEDURE SPName( @ColumnName varchar(100) ) AS
begin
SELECT * FROM XYZ
ORDER BY
  CASE WHEN @ColumnName='COl1' THEN @ColumnName 
       WHEN @ColumnName='COl2' THEN @ColumnName 
       WHEN @ColumnName='COl3' THEN @ColumnName 

END

Approach 2方法二


CREATE PROCEDURE SPName( @ColumnName varchar(100)  ) AS
begin
SELECT * FROM XYZ
where 1=1 AND ( COL1= @ColumnName or isnull(@ColumnName ,'')='')
end

Or Use two separate variable for Where Clause and Order by and use combination of above或者对 Where Clause 和 Order by 使用两个单独的变量,并使用上述组合

You can't mix dynamic SQL and regular SQL.您不能混合使用动态 SQL 和常规 SQL。 You need to make the whole thing dynamic SQL:你需要使整个事情动态 SQL:

create Procedure [dbo].[SearchList]  @command nvarchar(max) 
as begin
    declare @sql nvarchar(max);
    set @sql = N'
select *
from XYZ
' + @command;

    exec sp_executesql @sql;
end;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM