如何为以下场景编写SQL查询?

时间:2013-11-12 10:19:23

标签: sql sqlite

我正在为报告查看器编写此查询:

SELECT        Cust_Id, Clients_Title, Card_Number, Key_Person, Address_Current, Phone_Number, Mobile_Number, AreaLocation
FROM            Customer_New
WHERE        (Clients_Title = @Clients_Title) OR
                         (Address_Current = @Address_Current) OR
                         (Phone_Number = @Phone_Number) OR
                         (Mobile_Number = @Mobile_Number) OR
                         (AreaLocation = @AreaLocation)  

我想要的是:

  • 如果没有提供给报表查看器的参数,则将显示所有客户记录。
  • 如果提供了参数,则会实施OR条件。
  • 最后,如果在任何where条件下存在对比度,则不会显示任何记录。

谁能告诉我如何才能做到这一点?

2 个答案:

答案 0 :(得分:2)

SELECT Cust_Id, Clients_Title, Card_Number, Key_Person, Address_Current, Phone_Number, Mobile_Number, AreaLocation
FROM Customer_New
WHERE (Clients_Title = @Clients_Title   OR @Clients_Title IS NULL)
AND (Address_Current  = @Address_Current OR @Address_Current IS NULL) 
AND (Phone_Number     = @Phone_Number    OR @Phone_Number IS NULL) 
AND (Mobile_Number    = @Mobile_Number   OR @Mobile_Number IS NULL) 
AND (AreaLocation     = @AreaLocation    OR @AreaLocation  IS NULL) 

答案 1 :(得分:0)

正确答案是:

SELECT        Cust_Id, Clients_Title, Card_Number, Key_Person, Address_Current, Phone_Number, Mobile_Number, AreaLocation
    FROM            Customer_New
        where        (CASE
            WHEN @Clients_Title != ''   THEN Clients_Title=@Clients_Title
          ELSE
             NULL IS NULL
          END)
          AND(CASE
            WHEN @Address_Current != '' THEN Address_Current =@Address_Current
          ELSE
             NULL IS NULL
          END)
                  AND(CASE
            WHEN @Phone_Number != '' THEN Phone_Number=@Phone_Number
          ELSE
             NULL IS NULL
          END)
          AND(CASE
            WHEN @Mobile_Number != '' THEN Mobile_Number=@Mobile_Number
          ELSE
             NULL IS NULL
          END)
          AND(CASE
            WHEN @AreaLocation != '' THEN AreaLocation =@AreaLocation
          ELSE
             NULL IS NULL
          END)