SQL Server stored procedure return code oddity
- by gbn
Hello
The client that calls this code is restricted and can only deal with return codes from stored procs. So, we modified our usual contract to RETURN -1 on error and default to RETURN 0 if no error
If the code hits the inner catch block, then the RETURN code default to -4. Where does this come from, does anyone know...?
IF OBJECT_ID('dbo.foo') IS NOT NULL DROP TABLE dbo.foo
GO
CREATE TABLE dbo.foo (
KeyCol char(12) NOT NULL,
ValueCol xml NOT NULL,
Comment varchar(1000) NULL,
CONSTRAINT PK_foo PRIMARY KEY CLUSTERED (KeyCol)
)
GO
IF OBJECT_ID('dbo.bar') IS NOT NULL DROP PROCEDURE dbo.bar
GO
CREATE PROCEDURE dbo.bar
@Key char(12),
@Value xml,
@Comment varchar(1000)
AS
SET NOCOUNT ON
DECLARE @StartTranCount tinyint;
BEGIN TRY
SELECT @StartTranCount = @@TRANCOUNT;
IF @StartTranCount = 0 BEGIN TRAN;
BEGIN TRY
--SELECT @StartTranCount = 'fish'
INSERT dbo.foo (KeyCol, ValueCol, Comment) VALUES (@Key, @Value, @Comment);
END TRY
BEGIN CATCH
IF ERROR_NUMBER() = 2627 --PK violation
UPDATE
dbo.foo
SET
ValueCol = @Value, Comment = @Comment
WHERE
KeyCol = @Key;
ELSE
RAISERROR ('Tits up', 16, 1);
END CATCH
IF @StartTranCount = 0 COMMIT TRAN;
END TRY
BEGIN CATCH
IF @StartTranCount = 0 AND XACT_STATE() <> 0 ROLLBACK TRAN;
RETURN -1
END CATCH
--Without this, we'll send -4 if we hit the UPDATE CATCH block above
--RETURN 0
GO
--Run with RETURN 0 and fish line commented out
DECLARE @rtn int
EXEC @rtn = dbo.bar 'abcdefghijkl', '<foobar />', 'testing'
SELECT @rtn; SELECT * FROM dbo.foo
DECLARE @rtn int
EXEC @rtn = dbo.bar 'abcdefghijkl', '<foobar2 />', 'testing2'
--updated OK but we get @rtn = -4
SELECT @rtn; SELECT * FROM dbo.foo
--uncomment fish line
DECLARE @rtn int
EXEC @rtn = dbo.bar 'abcdefghijkl', '<foobar />', 'testing'
--Hit outer CATCH, @rtn = -1 as expected
SELECT @rtn; SELECT * FROM dbo.foo