SQL存储过程协助

时间:2017-03-28 03:43:38

标签: stored-procedures

我想要完成:

一个存储过程,它接受至少一个参数并根据参数中传递的值更新一个或多个记录。两个更新命令作为同一事务的一部分。如果事务出错则执行的错误处理程序。

使用此存储过程:

DROP PROCEDURE uspPatByState;
GO

CREATE PROCEDURE uspPatByState
     (@St varchar (2),  @state varchar (2) OUTPUT)
AS
BEGIN
    SELECT *
    FROM PATIENTS
    WHERE STATE = @St;

    IF @St IS NOT NULL
        SET @St = @state;

    UPDATE PATIENTS
    SET City = 'Los Angeles' 
    WHERE City = 'Honolulu'

    UPDATE PATIENTS
    SET ZipCode = '96801'
    WHERE ZipCode = '55555'

    SELECT *
    FROM PATIENTS
    WHERE STATE = @state        

    RETURN
END
GO

EXEC  uspPatByState  @St = 'CA' , @state= 'HI'

但它不起作用。我得到了:

Address1    Address2    City    State   ZipCode
1831 Universal Ave  NULL    Los Angeles CA  55555
1831 Universal Ave  NULL    Los Angeles CA  55555

我需要看到的是:

Address1      Address2  City    State   ZipCode
1831 Universal Ave  NULL    Honolulu    HI  96801
1831 Universal Ave  NULL    Honolulu    HI  96801

1 个答案:

答案 0 :(得分:0)

我不太明白你想要什么样的逻辑,或者你想做什么。但这是我如何使用事务和错误处理:

USE mydb;
DROP PROCEDURE uspPatByState;

GO

CREATE PROCEDURE uspPatByState
 (@St varchar (2),  @state varchar (2) OUTPUT)

AS
BEGIN
   BEGIN TRY
         BEGIN TRANSACTION
        IF(SELECT COUNT(*) FROM PATIENTS WHERE [state] = @st)
        BEGIN 
             UPDATE PATIENTS
                SET City =  'Los Angeles' 
                 WHERE City =  'Honolulu'

               UPDATE PATIENTS
                 SET ZipCode = '96801'
                    WHERE ZipCode = '55555'
        END ELSE 
        BEGIN 
          SET @state = @st
        END 
        SELECT * FROM PATIENTS WHERE STATE = @st 
         COMMIT TRANSACTION;
   END TRY
   BEGIN CATCH
         ROLLBACK TRANSACTION;
         SELECT ERROR_MESSAGE() AS ErrorMessage;
   END CATCH;
RETURN
END

GO

EXEC  uspPatByState  @St = 'CA' , @state= 'HI'