2015-12-14 145 views
1

我要堅持使用SQL Server存儲過程,它應該註冊一個用戶到數據庫(如果用戶不存在)。但是,成功執行該過程後,沒有數據被插入Users表中。存儲過程不會插入數據

如果我直接運行插入語句,它的工作原理。

下面是完整的程序代碼,在你問我之前,數據庫是空的。

--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 

我稱之爲傳遞所有參數。

謝謝!

回答

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的測試之間沒有任何關係。

+0

工作得很好!非常感謝你! –