减少多个if if语句

时间:2015-09-22 11:50:20

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

我有以下5个变量来检查条件。

示例

DECLARE @Col1 VARCHAR(10) = ''
DECLARE @Col2 VARCHAR(10) = ''
DECLARE @Col3 VARCHAR(10) = ''
DECLARE @Col4 VARCHAR(10) = ''
DECLARE @Col5 VARCHAR(10) = ''
DECLARE @String VARCHAR(MAX)


IF @Col1 = '' AND @Col2 = '' AND @Col3 = '' AND @Col4 = '' AND @Col5 = ''
BEGIN
    SET @String = ''
END
ELSE IF @Col1 <> '' AND @Col2 = '' AND @Col3 = '' AND @Col4 = '' AND @Col5 = ''
BEGIN
    SET @String = '@Col1'
END
ELSE IF @Col1 = '' AND @Col2 <> '' AND @Col3 = '' AND @Col4 = '' AND @Col5 = ''
BEGIN
    SET @String = '@Col2'
END
ELSE IF @Col1 = '' AND @Col2 = '' AND @Col3 <> '' AND @Col4 = '' AND @Col5 = ''
BEGIN
    SET @String = '@Col3'
END
ELSE IF @Col1 = '' AND @Col2 = '' AND @Col3 = '' AND @Col4 <> '' AND @Col5 = ''
BEGIN
    SET @String = '@Col4'
END
.....
.....
.....

如上所述,有很多概率。

如何减少多个if条件的发生?

2 个答案:

答案 0 :(得分:0)

我也想帮忙,抱歉采用不同的方法。 我把你的案子作为可叠加的东西,我到了这里。

DECLARE @Col1 VARCHAR(10) = 'test'
DECLARE @Col2 VARCHAR(10) = ''
DECLARE @Col3 VARCHAR(10) = 'tet'
DECLARE @Col4 VARCHAR(10) = ''
DECLARE @Col5 VARCHAR(10) = 't'
DECLARE @String VARCHAR(MAX)

CREATE TABLE #cols (ColName NVARCHAR(150), ColVal NVARCHAR(150))

INSERT INTO #cols VALUES ('@Col1',@Col1),('@Col2',@Col2),('@Col3',@Col3),('@Col4',@Col4),('@Col5',@Col5)

-- if you want to just concatenate things without a delimiter, you can do this
SET @String = (SELECT ColName AS [text()] FROM #cols WHERE ColVal != '' FOR XML PATH(''))

SELECT @String
-- output @Col1@Col3@Col5

-- if you want to concatenate things with a delimiter, you can do this
SET @String = (SELECT ColName + ', ' AS [text()] FROM #cols WHERE ColVal != '' FOR XML PATH(''))

SELECT @String
-- output @Col1, @Col3, @Col5

DROP TABLE #cols

希望这会增加一些想法。如果您有疑虑,请告诉我。

答案 1 :(得分:0)

您可以使用case expressions在一个声明中执行:

SELECT @String = CASE WHEN @Col1 = '' THEN 'col1' ELSE '' END +
                 CASE WHEN @Col2 = '' THEN 'col2' ELSE '' END +
                 CASE WHEN @Col3 = '' THEN 'col3' ELSE '' END +
                 CASE WHEN @Col4 = '' THEN 'col4' ELSE '' END +
                 CASE WHEN @Col5 = '' THEN 'col5' ELSE '' END