【问题标题】:Stored Procedure error - incorrect syntax near else存储过程错误 - else 附近的语法不正确
【发布时间】:2020-07-05 04:22:08
【问题描述】:

我正在处理我的第一个存储过程,它在 else 中显示错误(我在下面的 else 中有评论)。如果有人知道我如何修复错误,我将不胜感激。我试过在网上看,我认为这可能与我的开始/结束和 if/else 定位有关。不过,我很难找到一个类似的例子。

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE procedure [dbo].[SPName]
    @userid NVARCHAR(51)
AS 
    SET NOCOUNT ON

    DECLARE @return_status  INT

    IF @userid IS NULL OR @userid = 0
    BEGIN
        --fail
        SET @return_status = 1
    END

    IF  @return_status <> 1
    BEGIN
        IF EXISTS (SELECT login
                   FROM dbo.user_table
                   WHERE (@userid = login))
        --continue because its a good user
        ELSE  
            -- this is where it doesn't like the else
            SET @return_status = 1
    END

    BEGIN
        UPDATE dbo.U_MEMBER
        SET dbo.U_MEMBER.inac = 1,
            dbo.U_MEMBER.reg = @userid
        FROM dbo.U_MEMBER
        WHERE U_MEMBER.VF = 'REV'
    END

    RETURN 0

【问题讨论】:

  • 在第 27 行(在该特定批次中),您启动了一个 IF,但如果它是真的,您没有某事 可做。你直接去ELSE。当IF 评估为真时,IF 需要做一些事情。
  • 在不同的注释中,列的 3 部分命名将从 SQL Server 中弃用/删除。理想情况下,在引用列时坚持两部分命名和别名;那么当它发生时你就不会被抓住。
  • 另外,SET @return_status=1 的意图是让 SP 失败,因为它没有。事实上,第二次设置它什么也没做,因为它之后再也没有被引用过。似乎您最好使用THROW 作为第一个IF 和自定义错误消息。
  • U_MEMBER 和 user_table 之间的外键将否定存在检查的需要。这个架构和代码有很多需要改进的地方。建议对最佳做法进行一些调查。

标签: sql sql-server stored-procedures


【解决方案1】:

IF 语句如果等于 true 则无关:

IF  @return_status <> 1
BEGIN
    IF EXISTS(select login from dbo.user_table where  (@userid=login))
        --continue because its a good user
    ELSE  --this is where it doesn't like the else
        set @return_status = 1
    END
...

这在语法上是不正确的。如果IF 返回 true,TSQL 期望执行一条语句,在这种情况下,注释是不够的。

如果声明为真,则无需执行任何操作,只需切换到IF NOT EXISTS

IF  @return_status <> 1
BEGIN
    IF NOT EXISTS(select login from dbo.user_table where  (@userid=login))
    BEGIN
        set @return_status = 1
    END
...

否则,如果您想同时使用IF 语句的真假结果:

IF  @return_status <> 1
BEGIN
    IF EXISTS(select login from dbo.user_table where  (@userid=login))
    BEGIN
        -- Do something with the true outcome
    END
    ELSE
    BEGIN
        set @return_status = 1
    END
...

【讨论】:

    【解决方案2】:

    初始化@return_status变量,例如:

    DECLARE @return_status  INT
    
    --Initialize the variable with the expected value
    SET @return_status = 0
    
    IF @userid IS NULL OR @userid = 0
    BEGIN
    --fail
        SET @return_status=1
    END
    

    【讨论】:

    • 这很有帮助,谢谢。这不是我有错误的原因。我将接受另一个答案,并投票赞成您的答案有帮助。
    猜你喜欢
    • 2010-09-21
    • 1970-01-01
    • 2020-06-23
    • 1970-01-01
    • 2022-01-06
    • 1970-01-01
    • 1970-01-01
    • 2021-10-25
    • 2014-05-27
    相关资源
    最近更新 更多