borkovski
borkovski

Reputation: 978

TSQL RAISERROR as warning

I'm looking through questions for Microsoft's 70-761 exam and I came across a troublesome one. The question asks to 'produce a warning if '.

It seems obvious that I should use RAISERROR (or THROW) statement. My question is - what severity should I use to fulfill this requirement?

I'm aware that 16 is default for THROW, but I hesitate to call it a warning. Maybe RAISERROR with severity set to 10 would be more appropriate?

Upvotes: 5

Views: 8854

Answers (2)

Henrik Høyer
Henrik Høyer

Reputation: 1652

The SQL you are looking for:

RAISERROR('Warning: <your message>', 0,0) WITH NOWAIT

If you need anything "dynamic" in your message, you need something like:

DECLARE @messageString varchar(max)     
set @messageString = 'Warning: The time is ' + convert(varchar(max), getdate(), 120) 
RAISERROR(@messageString,0,0) WITH NOWAIT

The WITH NOWAIT part is important, if you want the message to appear before any surrounding transaction completes.

Upvotes: 2

MK_
MK_

Reputation: 1169

You should've simply checked the documentation: https://learn.microsoft.com/en-us/sql/relational-databases/errors-events/database-engine-error-severities

Basically what your answer should be is RAISERROR with severity 0-10 (or rather, 0-9).

With THROW you can't handle severities because the default one is 16. Therefore, it can't be used to throw a warning.

Upvotes: 4

Related Questions