TSQL:if语句中的select语句

时间:2012-01-24 16:55:56

标签: sql tsql function if-statement case

我在函数中有这个结构:

INSERT INTO @TheTable
    SELECT DISTINCT

        @Number AS Number,

        @Name AS Name

    FROM MYTABLE 
    WHERE id = @id

我需要在这个结构中添加执行另一个函数的结果,我需要你的帮助才能这样做。

在@Name AS Name下面,我应该添加类似这样的内容

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

如何将其转换为TSQL?

万分感谢!

3 个答案:

答案 0 :(得分:7)

猜猜这就是你想要的......

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

答案 1 :(得分:1)

SELECT语句中没有IF语句。相反,你会想要使用CASE。

MSDN Documentation on CASE

答案 2 :(得分: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。