Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create a concatenated message in a SQL Server throw?

I have this code:

IF (@CurrentResult != 'N' AND @CurrentResult != 'F')
    THROW 50002, 'Question should be unmarked or incorrect', 1

Can someone explain to me how I can also give the @CurrentResult in the error message I throw?

What I would like is for the message to appear like:

Question result is 'X'. It should be unmarked or incorrect?

Where X is the value of @CurrentResult.

like image 257
Samantha J T Star Avatar asked Feb 13 '15 18:02

Samantha J T Star


2 Answers

You cannot concatenate strings inside a THROW statement.

What you need to do is create a variable and assign your whole error message to it:

DECLARE @Message NVARCHAR(100)
SET @Message = N'Question result is ''' + @CurrentResult + '''. It should be unmarked or incorrect?'

IF (@CurrentResult != 'N' AND @CurrentResult != 'F')
    THROW 50002, @Message, 1
like image 83
rory.ap Avatar answered Oct 24 '22 03:10

rory.ap


Edited to reflect setting message variable first:

DECLARE @Message varchar(100)
SET @Message = 'Question result is ' + cast(@CurrentResult, varchar(100)) + '. It should be unmarked or incorrect.'

IF (@CurrentResult != 'N' AND @CurrentResult != 'F')
    THROW 50002,@Message,1

Casting to varchar will keep the text value of whatever @CurrentResult is. Set the size accordingly.

like image 3
Phoenix Avatar answered Oct 24 '22 03:10

Phoenix