存储过程不会插入数据

时间:2015-12-14 19:35:51

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

我对SQL Server存储过程感到困惑,它应该将用户注册到数据库中(如果用户尚未存在)。但是,在成功执行该过程后,没有数据插入Users表。

如果我直接运行insert语句,它就可以工作。

下面是完整的程序代码,在你问我之前,数据库是空的。

--USERS
CREATE PROCEDURE [dbo].[RegisterUser]
  @NAME VARCHAR(255),
  @PHONENUMBER VARCHAR(255),
  @STATUS INT OUT,
  @REMAININGDAYS INT OUT
AS
BEGIN
    SET NOCOUNT ON;

    UPDATE Users WITH (serializable) 
    SET Name = @NAME
    WHERE PhoneNumber LIKE @PHONENUMBER

    SET @REMAININGDAYS = 0

    IF @@rowcount = 0
    BEGIN
        INSERT INTO Users (Name, PhoneNumber, RegisterDate) 
        VALUES (@NAME, @PHONENUMBER, GETDATE())

        SET @STATUS = 0
        SET @REMAININGDAYS = 40
    END
    ELSE
    BEGIN
         DECLARE @USERID BIGINT
         DECLARE @EXP DATETIME

         SELECT TOP 1 
             @USERID = USERID 
         FROM USERS 
         WHERE PhoneNumber LIKE @PHONENUMBER

         SELECT TOP 1 
             @EXP = DATEADD(day, DAYS, REGISTERDATE) 
         FROM SUBSCRIPTIONS
         WHERE USERID = @USERID 
         ORDER BY [REGISTERDATE]

         IF @EXP IS NULL
         BEGIN
             SELECT TOP 1 
                 @EXP = DATEADD(day, 40, REGISTERDATE) 
             FROM USERS 
             WHERE USERID = @USERID

             IF GETDATE() < @EXP
             BEGIN
                 SET @STATUS = 0
                 SET @REMAININGDAYS = DATEDIFF(day, GETDATE(), @EXP)
             END
             ELSE
             BEGIN
                 SET @STATUS = -1
             END
         END
         ELSE
         BEGIN
             IF GETDATE() < @EXP
                SET @STATUS = 1
             ELSE
                SET @STATUS = -1
         END
    END
END

我称之为传递所有参数。

谢谢!

1 个答案:

答案 0 :(得分:6)

进行简单分配的语句始终将@@ ROWCOUNT值设置为1. @@ROWCOUNT (Transact-SQL)

所以

DECLARE @i int
SET @i = 0
PRINT @@ROWCOUNT

打印1。

DECLARE @RC INT
UPDATE Users WITH (serializable) SET Name = @NAME
WHERE PhoneNumber LIKE @PHONENUMBER
SET @RC = @@ROWCOUNT

SET @REMAININGDAYS = 0

IF @@RC = 0
BEGIN
   INSERT INTO Users  <etc...>

或者将SET @REMAININGDAYS = 0移到更新语句之上,以便更新和@@ROWCOUNT的测试之间没有任何内容。