2012-01-24 116 views
3

裏面我有這個結構的函數內部:TSQL:if語句選擇插入

INSERT INTO @TheTable 
    SELECT DISTINCT 

     @Number AS Number, 

     @Name AS Name 

    FROM MYTABLE 
    WHERE id = @id 

我需要添加到這種結構的結果來執行其他功能的,我需要你的幫助,這樣做。

下面的@Name AS名,行我要補充的是這樣的

IF (dbo.anotherFunction(@id)==1) 
@NewVisitor AS NewVisitor 
ELSE 
@NewVisitor AS NoNewVisitor 

我怎樣才能轉化爲TSQL這個?

非常感謝!

+0

因此,你的'INSERT'沒有引用'MYTABLE'中的任何列,並且你帶回了'id'匹配的所有行,然後用'DISTINCT'除掉一個除外的所有行?只要使用'IF EXISTS(...)' –

+1

是@TheTable中的newVisitor和noNewVisitor 2不同列,你會好得多嗎?所以你想插入@newVisitor到2列之一? – Beth

+0

這只是一個例子,請教我如何去做if語句或類似的結構。非常感謝 – user712027

回答

6

猜測這是你想要的...

INSERT INTO @TheTable 
    SELECT DISTINCT 
     @Number AS Number, 
     @Name AS Name, 
     case when (dbo.anotherFunction(@id)=1) then @NewVisitor else null end as NewVisitor, 
     case when (dbo.anotherFunction(@id)<>1) then @NewVisitor else null end AS NoNewVisitor 
    FROM MYTABLE 
    WHERE id = @id 
+0

非常感謝,這就是我需要的! – user712027

0

這個問題沒有什麼意義,我(爲什麼所有的變量,有什麼事列呢?),但你可以這樣來做:

IF (dbo.anotherFunction(@id)==1) 
    INSERT INTO @TheTable 
    SELECT DISTINCT 
     @Number AS Number, 
     @Name AS Name, 
     @NewVisitor AS NewVisitor 
    FROM MYTABLE 
    WHERE id = @id 
ELSE 
    INSERT INTO @TheTable 
    SELECT DISTINCT 
     @Number AS Number, 
     @Name AS Name, 
     @NewVisitor AS NoNewVisitor 
    FROM MYTABLE 
    WHERE id = @id 

或者使用兩個CASE語句選擇NewVisitor和NoNewVisitor。