2013-02-22 136 views
0

我需要一個if語句添加到我的過程中,這樣的事情SQL你可以把一個if語句放在select過程中嗎?

CREATE PROCEDURE [dbo].[myProcedure] 
    @name VARCHAR(8000) = NULL 
,@lname VARCHAR(8000) = NULL 
,@flag CHAR(1) = NULL 


AS 
BEGIN 
SET NOCOUNT ON; 
    WITH t 
    (name 
    ,lname 
    ) 

AS 
(
    SELECT DISTINCT 
    * FROM mytable 
    WHERE 
    (@name IS NULL OR @name = name) 
    IF @flag = 'c' 
    BEGIN 
     AND (@lname IS NULL OR @lname = 'Doe') 
    END 
    ELSE 
    BEGIN 
    AND (@lname IS NULL OR @lname = lname) 
    END 
) 

正如你可以根據我使用這種或那種方式將lname領域的標誌見。 我在if部分收到錯誤..是不是我在這裏不能使用if語句? 如果不是,我該如何替換if語句?

非常感謝

回答

2

你可以這樣說:

SELECT DISTINCT * 
FROM mytable 
WHERE 
    (@name IS NULL OR @name = name) 
    AND 
    (
     (@flag = 'c' AND (@lname IS NULL OR @lname = 'Doe')) 
     OR 
     (@flag != 'c' AND (@lname IS NULL OR @lname = lname)) 
    ) 
+0

工作得很好,謝謝你教我! – user712027 2013-02-22 16:11:01

+0

@ user712027 - np,很高興能幫到你! – sgeddes 2013-02-22 16:15:57

0

只是提供一個備用的答案(因爲我覺得一個CASE語句是真正的模擬到SQL IF語句):

SELECT 
DISTINCT 
    * 
FROM 
    mytable 
WHERE 
    (@name IS NULL OR @name = name) 
    AND 
    (@lname is NULL OR @lname = 
    CASE 
     WHEN @flag ='c' THEN 'Doe' 
     ELSE lname 
    END 
    ) 
0

試試這個

.... 
WHERE 
(@name IS NULL OR @name = name) AND 
(
    (@flag = 'c' AND (@lname IS NULL OR @lname = 'Doe')) OR 
    (@lname IS NULL OR @lname = lname) 
) 
相關問題