仅在满足条件

时间:2016-05-17 10:57:05

标签: sql sql-server sql-server-2008

我想要一个没有固定列数的选择。 仅当变量 @check = 1

时,才应选择列OptionalColumn

这就是我所拥有的(语法很差但可能解释了我的问题)

SELECT 
    Column1, Column2,
    (IF @Check = 1
       BEGIN OptionalColumn END)
FROM table

仅在@Check = 1时才拥有它,如果@Check = 0则不具备它是至关重要的。 它可行吗?

3 个答案:

答案 0 :(得分:2)

You could do this with an IF ELSE block like this;

CREATE TABLE #table (Column1 varchar(10), Column2 varchar(10))
INSERT INTO #table
VALUES
('column1', 'column2')

DECLARE @Check bit; SET @Check = 0

IF @Check = 1 
(SELECT Column1, Column2
FROM #table)

ELSE

(SELECT Column1
FROM #table)

Change the variable from 0 to 1 for testing to see the change in number of columns.

答案 1 :(得分:2)

Rich Benner gave you a good solution, as an alternative you can use dynamic sql like that :

DECLARE  @sqlvar VARCHAR(100)
select @Sqlvar= ' SELECT Collumn1, Collumn2 '+IIF (@check=1,',OptionalCollumn','')+' from TABLE';
EXECUTE sp_executesql @sqlvar 

For reference on sp_ executesql look: [https://msdn.microsoft.com/it-it/library/ms188001(v=sql.120).aspx]

答案 2 :(得分:1)

可以使用IF ELSE块。请试试这个。

User