使用多个if else和不同表的where存储过程

时间:2013-11-08 09:44:02

标签: sql stored-procedures

ALTER PROCEDURE [dbo].[SP_Something]
(
    @Search_Text VARCHAR(4000),
    @FILTER INT
)
AS
BEGIN  
    SELECT  Customer_Information
    FROM    Customer
    LEFT OUTER JOIN Something K 
            ON  K.Something _Id= Something_Id2
    LEFT OUTER JOIN  Something3 KS 
            ON KS.Something_Id =Something_Id3
    WHERE
        (Filter = 1 AND Customer_İnformation LIKE '%' + @Search_Text + '%')
        OR
        (Filter = 2 AND Customer_name LIKE '%' + @Search_Text + '%')
        OR
        (Filter = 3 AND Customer_Adress LIKE '%' + @Search_Text + '%')
END

我从客户表获取所有数据。

我需要从 PRODUCT_TABLE 获取以下代码的数据

(Filter = 3 AND Customer_Adress LIKE '%' + @Search_Text + '%')
from PRODUCT_TABLE

我怎样才能在Ms Sql中的“where”里面实现这个?

任何帮助将不胜感激。

感谢。

2 个答案:

答案 0 :(得分:1)

ALTER PROCEDURE [dbo].[SP_Something]
(
    @Search_Text VARCHAR(4000),
    @FILTER INT
)
AS
BEGIN  
    IF Filter IN (1,2)
    SELECT  Customer_Information
    FROM    Customer
    LEFT OUTER JOIN Something K 
            ON  K.Something _Id= Something_Id2
    LEFT OUTER JOIN  Something3 KS 
            ON KS.Something_Id =Something_Id3
    WHERE
        (Filter = 1 AND Customer_İnformation LIKE '%' + @Search_Text + '%')
        OR
        (Filter = 2 AND Customer_name LIKE '%' + @Search_Text + '%')
        OR
        (Filter = 3 AND Customer_Adress LIKE '%' + @Search_Text + '%')

    IF Filter = 3
    SELECT  YourField
    FROM    ProductTable
    WHERE
        (Filter = 3 AND YourSearchField LIKE '%' + @Search_Text + '%')

END

答案 1 :(得分:0)

ALTER PROCEDURE [dbo].[SP_Something]
(
    @Search_Text VARCHAR(4000),
    @FILTER INT
)
AS
BEGIN  
    SELECT  Customer_Information
    FROM    Customer
    LEFT OUTER JOIN Something K 
            ON  K.Something _Id= Something_Id2
    LEFT OUTER JOIN  Something3 KS 
            ON KS.Something_Id =Something_Id3
    LEFT OUTER JOIN  PRODUCT_TABLE P
            ON P.Something_Id = KS.Something_Id3

    WHERE
        (Filter = 1 AND Customer_İnformation LIKE '%' + @Search_Text + '%')
        OR
        (Filter = 2 AND Customer_name LIKE '%' + @Search_Text + '%')
        OR
        (Filter = 3 AND Customer_Adress LIKE '%' + @Search_Text + '%')
        OR
        (P.Filter = 3 AND P.Customer_Adress LIKE '%' + @Search_Text + '%')

END

我认为你在这里缺少的另一件事是,在你的Where子句中你没有提到任何关于哪个Filter来自哪个表,在列名之前使用表别名就像我拥有它使代码更容易阅读和更容易维护并解决了列歧义。