Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know TSQL Stored Procedure Update Executed

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.

like image 200
Jaiesh_bhai Avatar asked Oct 02 '13 19:10

Jaiesh_bhai


3 Answers

Have you checked out @@ROWCOUNT? Might be what you're looking for (see this for details: http://technet.microsoft.com/en-us/library/ms187316.aspx). Basically it returns the number of rows affected by the last statement. I'd imagine if it were not "successful", it would be zero rows.

like image 132
rory.ap Avatar answered Oct 12 '22 13:10

rory.ap


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
like image 34
The Hill Boy Avatar answered Oct 12 '22 14:10

The Hill Boy


You can use a try catch block and log the success or failure to a table.

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
like image 39
Farnam Avatar answered Oct 12 '22 13:10

Farnam