简体   繁体   English

如何根据存储过程中的其他条件将零件追加到查询中

[英]How to append a part to query based of if else conditions within a stored procedure

What I have to achieve is something like appending string to existing variable for eg : 我要实现的是将字符串附加到现有变量,例如:

string abc = "good";
abc += "afternoon";

so that the final output will be "good afternoon" 这样最终输出将是“下午好”

I have written the following stored procedure : 我已经编写了以下存储过程:

CREATE OR ALTER PROCEDURE [dbo].[sp_getPropertyContactUsDetails]
    (@isDeleted CHAR(1), 
     @cName VARCHAR(MAX)) 
AS
BEGIN
    SET NOCOUNT ON;
    --DECLARE @mainQ varchar(max)

    SELECT 
        pcd.col1, pcd.col2,.....
        CASE
           WHEN pcd.col1 = 'abc'
              THEN (SELECT pname FROM tbl_pd1 WHERE id = pcd.id)
           WHEN pcd.col2 = 'def'
              THEN (SELECT pname FROM tbl_pd2 WHERE id = pcd.id)
        END AS 'pname',
    FROM  
        tbl_pcd pcd 
    WHERE 
        pcd.isDeleted = @isDeleted

Now I want to append a part to the query based on if else condition as following: 现在,我要根据是否满足以下条件将一部分添加到查询中:

IF @cName IS NOT NULL
THEN 

append following part to the select query : 将以下部分附加到选择查询:

ORDER BY ID DESC 

IF @cName IS NULL then don't append the part! 如果@cName为NULL,则不要追加零件!

I have tried with declaring a parameter as : 我尝试将参数声明为:

DECLARE @mainQ VARCHAR(MAX)

Then I am doing something like : 然后我正在做类似的事情:

SET @mainQ = 'The select statement as specified above in the stored procedure'

T hen for append part : 附加部分:

IF @cName IS NOT NULL
    SET @mainQ = @mainQ + ' ORDER BY ID DESC'

END (END statement of stored procedure)

Can anyone help me out with the following situations, how to append a part to original query based on if else condition?? 谁能在以下情况下为我提供帮助,如何根据其他条件将零件追加到原始查询中?

Note that stored procedure may contain multiple if statements! 请注意,存储过程可能包含多个if语句!

If you just want add to order by clause then you can use something like - 如果您只想添加到order by子句,则可以使用-

ORDER BY
  CASE WHEN @cName IS NOT NULL 
  THEN ID 
  END DESC

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

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