9

How can I check if my TSQL stored procedure updated within the stored procedure in order to create a proper message?

Example:

ALTER PROCEDURE [dbo].[pUpdate]
            @id uniqueidentifier, 
            @status int,
            @message VARCHAR(100) OUTPUT
AS
BEGIN
    SET NOCOUNT ON;

    UPDATE [database].[dbo].[user]
    SET status = @status
    WHERE Id = @id
END

IF (SUCCESSFUL)
BEGIN
    @message = 'Success!'
END

What are some possible ways to check if successful without using the parameters again?

This is what I currently use:

  SELECT COUNT(*)
    WHERE status = @status AND id = @id

Are there any other ways? I want to know for my knowledge and reference. Thanks.

4

4 回答 4

20

你检查了@@ROWCOUNT吗?可能是您正在寻找的(有关详细信息,请参阅:http ://technet.microsoft.com/en-us/library/ms187316.aspx )。基本上它返回受最后一条语句影响的行数。我想如果它不“成功”,它将是零行。

于 2013-10-02T19:54:12.400 回答
4
ALTER PROCEDURE [dbo].[pUpdate]
            @id uniqueidentifier, 
            @status int,
            @message VARCHAR(100) OUTPUT
AS
BEGIN
    SET NOCOUNT ON;

    UPDATE [database].[dbo].[user]
    SET status = @status
    WHERE Id = @id
END

IF (@@ROWCOUNT > 0)
BEGIN
     @message = 'Success!'
END
ELSE 
BEGIN
    @message = 'Not success!'
END
于 2013-10-09T10:44:50.647 回答
1

您可以使用 try catch 块并将成功或失败记录到表中。

BEGIN TRY
    BEGIN TRANSACTION
    -- Add Your Code Here
    -- Log Success to a log table
    COMMIT
END TRY
BEGIN CATCH
    -- Log failure to a log table
    ROLLBACK
END CATCH
于 2013-10-02T19:54:33.380 回答
0

我会使用@@ERROR系统变量来检查最后一句话是否成功(错误#= 0)或不(错误#> 0):

USE Database;
GO

BEGIN
    UPDATE TableName
    SET ColumnA = 4
    WHERE ColumnB = 1;
END

IF (@@ERROR = 0)
BEGIN
    PRINT N'Successfull Update';
    GO
END

您可以在此处深入了解 Microsoft MSDN:http ://technet.microsoft.com/es-es/library/ms188790.aspx

于 2013-10-02T20:08:54.650 回答