SQL IF语句问题

时间:2012-04-23 02:42:16

标签: sql

我的SQL语句出了什么问题?

ALTER PROCEDURE prGetDocById
    @Nbr varchar(100),
    @Type uniqueidentifier,
    @TotalRecord int output
AS
BEGIN
    IF(@Type is null)
    BEGIN
    (
        SELECT @TotalRecord = COUNT(Category) FROM Document where Nbr = @Nbr and 
            Type = (case when @Type IS not null then @Type else null end) 
        SELECT * from Document
    )
    end
    else
    begin
    (
        ...
    )
    end
end

它给了我这个错误:

  

Msg 156,Level 15,State 1,Procedure prGetDocById,Line 12
  关键字'SELECT'附近的语法不正确。
  Msg 102,Level 15,State 1,Procedure prGetDocById,Line 13
  ')'附近的语法不正确。
  Msg 102,Level 15,State 1,Procedure prGetDocById,第19行   ')'附近的语法不正确。

我想从IF语句开始,并且还需要返回输出,所以在我的语句中会有两个select语句。

如果我在没有IF语句的情况下编写它,一切正常。

1 个答案:

答案 0 :(得分:3)

您的代码应遵循以下结构:

IF( 1 = 1) BEGIN
    SELECT 1;
END
ELSE BEGIN
    SELECT 2;
END

在第二个条件中有大括号是不合法的,并且在特定情况下,第一个条件体中的括号不合法/必要(至少不在MS SQL Server中)。

括号用法

-- legal but pointless most of the time
IF( 1 = 1) BEGIN
(
    SELECT 1
)
END

-- illegal
IF( 1 = 1) BEGIN
(
    SELECT 1;
)
END

-- illegal
IF( 1 = 1) BEGIN
(
    SELECT 1
    SELECT 2
)
END

特定查询

我不明白这里的逻辑(CASE似乎毫无意义),但我认为这在语法上是正确的。请注意,我将[Type]放在括号中,因为它是一个保留字。

IF( @Type IS NULL ) BEGIN
    SELECT 
        @TotalRecord = COUNT(Category) 
    FROM Document
    where Nbr = @Nbr and [Type] = (case when @Type IS not null then @Type else null end);

    SELECT * from Document;
END
ELSE BEGIN
    SELECT 0;
END