简体   繁体   English

SQL存储过程IF ELSE逻辑错误

[英]SQL Stored Procedure IF ELSE logic error

I am trying to implement an insert stored procedure. 我正在尝试实现插入存储过程。 Basically, how it works is the stored procedure will check whether the record exists or not, then proceed to perform insert. 基本上, stored procedure将如何工作,将检查记录是否存在,然后继续执行插入操作。 A variable @status will be used as indicator. 变量@status将用作指标。 However, I found out a particular problem with this query is that when I execute the query , it will return the result @status = 1 no matter the data existed or not. 但是,我发现此query一个特殊问题是,当我执行query ,无论数据是否存在,它将返回结果@status = 1 However, the INSERT function is fine without any problems just the @status . 但是, INSERT函数很好,没有任何问题,只是@status The following is my implementation: 以下是我的实现:

CREATE PROCEDURE save_proc
(
  @userid varchar(10)
  @name varchar(30)
)

AS

DECLARE @status int

  if exists ( SELECT * FROM table1 where userID = @userid AND userName = @name)
    SET @status = 0

  else
    INSERT INTO table1 (userID, userName) VALUES (@userid, @name)
    SET @status = 1

SELECT @status
else
begin
    INSERT INTO table1 (userID, userName) VALUES (@userid, @name)
    SET @status = 1
end

Modify code as above. 修改上面的代码。 You haven't defined scope of your else. 您尚未定义其他范围。 It was upto insert statement only. 这仅取决于插入语句。 SET @status = 1 was executed everytime 每次执行SET @status = 1

Try to put it in BEGIN END 尝试将其放在BEGIN END

CREATE PROCEDURE save_proc
(
  @userid varchar(10)
  @name varchar(30)
)

AS

DECLARE @status int

  if exists ( SELECT * FROM table1 where userID = @userid AND userName = @name)
    SET @status = 0

    else
    begin
        INSERT INTO table1 (userID, userName) VALUES (@userid, @name)
        SET @status = 1
    end

If you are not putting the BEGIN END then the scope of your else statement is just the next line which is getting executed ie, INSERT INTO table1 (userID, userName) VALUES (@userid, @name) is only under the scope of else block. 如果您未将BEGIN END INSERT INTO table1 (userID, userName) VALUES (@userid, @name)则else语句的作用域仅是要执行的下一行,即INSERT INTO table1 (userID, userName) VALUES (@userid, @name)仅在else块的作用域内。 And SET @status = 1 is outside the scope of else block. SET @status = 1else块的范围之外。 So once the else block executes the next query will be executed which is SET @status = 1 因此,一旦执行else块,将执行下一个查询,即SET @status = 1

On a side note: 附带说明:

When you are checking for if exists then don't use the * wildcard. 当您检查if exists请不要使用*通配符。 Instead you can use 1 ie, 相反,您可以使用1

if exists ( SELECT 1 FROM table1 where userID = @userid AND userName = @name)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM