0

你甚至可以在这样的选择中放置一个 if 语句,或者你必须使用 Case 语句来完成我在这里尝试做的事情吗?我目前收到语法错误:

Select 
    field1,
    field2,
    If( @CurrentDate = @lastDate and @CurrentWeek = @lastWeek) 
              select @CurrentWeek,
    .... rest of select statement
4

4 回答 4

2

您将需要使用CASE. 但是请注意,您可以将 CASE 用作 aSWITCH和 a IF ... THEN ... ELSEIF ... ELSE,因此您具有很大的灵活性。

例如:

DECLARE @flag INT
SET @flag = 1

-- Switch
SELECT CASE @flag WHEN 1 THEN 'Condition True' 
                  WHEN 0 THEN 'Condition FALSE' 
                  ELSE 'Condition Invalid' 
       END

-- If / elseif / else
SELECT CASE WHEN @flag = 1 
                 THEN 'Condition True' 
            WHEN @flag = 0 AND @@SERVERNAME = 'TotallyUnrelatedToFlag' 
                 THEN 'Condition FALSE' 
            ELSE 'Condition Invalid' 
       END

在您的示例中,您似乎需要一些类似的东西

Select 
    field1,
    field2,
    CASE WHEN (@CurrentDate = @lastDate and @CurrentWeek = @lastWeek) 
         THEN @CurrentWeek
         ELSE NULL
    END As field3
于 2012-10-10T14:29:39.677 回答
1

听起来你想要一个CASE声明

Select 
    field1,
    field2,
    case when @CurrentDate = @lastDate and @CurrentWeek = @lastWeek
         then @CurrentWeek else '' end
    .... rest of select statement

如果你想使用一个IF语句,那么你会想要使用这样的东西:

If (@CurrentDate = @lastDate and @CurrentWeek = @lastWeek)
  begin
    -- place the one select statement here
    select ...from
  end
else
  begin
     -- place the alternate select here
     select... from
  end
于 2012-10-10T14:26:00.913 回答
1

You must use a case statement instead. The IF...ELSE construct in TSQL can be used to conditionally execute a SQL statement. It cannot be used within a SQL statement. Please read the documentation which makes this clear.

于 2012-10-10T14:27:46.307 回答
0

尝试这个:

Select 
    field1,
    field2,
    CASE WHEN @CurrentDate = @lastDate and @CurrentWeek = @lastWeek THEN @CurrentWeek ELSE '' END as Week,
于 2012-10-10T14:26:31.917 回答