Possible Duplicate:
How do I find out the _exact_ error from SQL Server
One of our clients desires custom error messages upon UNIQUE KEY violations.
Given the following scenario:
CREATE TABLE [dbo].[Pip]
(
id int IDENTITY(1,1) NOT NULL,
code NVARCHAR(50) NOT NULL,
CONSTRAINT [PK_Pip] PRIMARY KEY ([id]),
CONSTRAINT [UQ_Pip_Code] UNIQUE([code]),
)
BEGIN TRY
INSERT INTO Pip(code) VALUES('TEST')
INSERT INTO Pip(code) VALUES('TEST')
END TRY
BEGIN CATCH
DECLARE @error INT, @message VARCHAR(4000), @xstate INT;
SELECT @error = ERROR_NUMBER(), @message = ERROR_MESSAGE(), @xstate = XACT_STATE();
IF @errorNumber = 2627 OR @errorNumber = 2601 BEGIN
RAISERROR('<custom unique key violation error message>', 16, 1)
END
END CATCH
What I would need is the name of the unique key being violated in the CATCH-section, so that I can specify an error message per defined unique key.
Obviously, I could manually add checks in the different stored procedures accessing this table - however, this leads to less maintainable code, and is not something we would want.
Is there such a possibility in SQL Server (2008R2)?
I've thought about parsing ERROR_MESSAGE() with some sort of regex, based on the sys.messages-table. However, this feels like the wrong thing to do.
Thanks!
Sander