嵌套如果在存储过程中导致语法错误

时间:2012-09-19 17:38:52

标签: sql-server sql-server-2005 stored-procedures

我正在创建一个存储过程,它查询表“条目”。 proc具有参数@ID,它是一个int,而@APPROVED是一个参数。我正在使用SQL Server 2005

如果批准是假的,我想做一些不同于它的事情。我写了以下内容。当我尝试创建它时,我得到“关键字'END'附近的语法不正确。”。

如果我删除了嵌套,如果错误消失,但是从我读过的内容来看,这是完全有效的语法。谁能告诉我哪里出错了?

CREATE Procedure [dbo].[GetEntry](@ID int,@APPROVED bit)
AS
IF @APPROVED = 0
BEGIN 
    --see if the unapproved entry has already been viewed 
    IF (SELECT COUNT(*) 
    FROM [dbo].[Entries]
    WHERE EntryId = @ID AND Approved = @APPROVED AND Viewed = 0) > 0
    BEGIN

    END

END

任何帮助都会非常感激。谢谢!

2 个答案:

答案 0 :(得分:1)

您需要在BEGIN/END内执行某项操作,并且更有效的检查是EXISTS与手动获取计数(必须扫描整个聚集索引)相比。如果结果是2或5或27,654,你真的不在乎,对吧?

IF EXISTS (SELECT 1 FROM dbo.Entries WHERE ...)
BEGIN
    PRINT 'It exists!';
END

答案 1 :(得分:1)

您必须在BEGIN/END中执行某些操作,它不能为空:

CREATE Procedure [dbo].[GetEntry](@ID int,@APPROVED bit)
AS
IF @APPROVED = 0
BEGIN 
    --see if the unapproved entry has already been viewed 
    IF (SELECT COUNT(*) 
            FROM [dbo].[Entries]
            WHERE EntryId = @ID AND Approved = @APPROVED AND Viewed = 0) > 0
    BEGIN
        -- do something here
        select *
        from [dbo].[Entries]
    END

END