使用if with else的存储过程

时间:2013-11-08 08:32:43

标签: sql stored-procedures if-statement

我一直在尝试使用存储过程来搜索数据。

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

// If @FILTER=1 i want to search below

 Customer_İnformation LIKE '%' + @Search_Text + '%'

// If @FILTER=2 i want to search below

Customer_name LIKE '%' + @Search_Text + '%'

// If @FILTER=3 i want to search below

Customer_Adress LIKE '%' + @Search_Text + '%'

如何在如果条件下使用哪里

任何帮助将不胜感激

谢谢。

2 个答案:

答案 0 :(得分:2)

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

答案 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
  WHERE
  CASE @FILTER 
     WHEN 1 THEN Customer_İnformation
     WHEN 2 THEN Customer_Name
     WHEN 3 THEN Customer_Address
  END LIKE '%' + @Search_Text + '%';
END