如何利用if语句的结果

时间:2015-08-21 05:28:02

标签: sql sql-server tsql

我这里有3个清单。想要进行List 1和3或2和3的条件组合,当我使用下面的代码时似乎没问题。

declare @Condition varchar(10) = NULL

if @Condition IS NULL
    select * from List1
else 
    select * from List2
union 
select * from List3

但是,如果我想通过将最终结果插入表中来存储最终结果,则会返回if语句的语法错误。有没有更好的方法可以做到这一点?

declare @Condition varchar(10) = NULL

declare @CombiList table (Value varchar(10))
insert into @CombiList

if @Condition IS NULL
    select * from List1
else 
    select * from List2
union 
select * from List3

3 个答案:

答案 0 :(得分:1)

喜欢这个

INSERT INTO @CombiList
SELECT *
FROM   list1
WHERE  @Condition IS NULL
UNION
SELECT *
FROM   List2
WHERE  @Condition IS NOT NULL
UNION
SELECT *
FROM   List3
WHERE  @Condition IS NOT NULL

答案 1 :(得分:0)

您需要为每个条件创建两个单独的INSERT语句:

if @Condition IS NULL
    insert into @CombiList
        select * from List1
else 
    insert into @CombiList
        select * from List2
        union 
        select * from List3

答案 2 :(得分:-1)

如果您的真正问题涉及更复杂的语句并且代码可以包装在存储过程中,那么构建和执行动态T-SQL语句可以降低代码的复杂性。

例如:

DECLARE @DynamicTSQLStatement NVARCHAR(MAX);

...

-- some statements that are executing always
SET @DynamicTSQLStatement = '....'

-- conditions

IF ... 
   SET @DynamicTSQLStatement = @DynamicTSQLStatement + '.....'
ELSE
   ...
   SET @DynamicTSQLStatement = @DynamicTSQLStatement + '.....'

EXEC sp_executesql @DynamicTSQLStatement