How to use variables in SQL raiserror
Asked Answered
F

4

15

I am trying to show my int variables in raiserror @MaxAmount and @MinAmount

Raiserror('Total Amount should be less than %s and Greater than %s',16,1,@MaxAmount,@MinAmount)

But Im getting error:

Must declare the scalar variable "@MaxAmount".

Fleda answered 16/9, 2015 at 10:3 Comment(2)
its basic, you must declare variables before using it in query.Normally
I did declare but there was a typo when I used it in raiserror. Solved!Fleda
S
16

%s is used for varchar and your variable is of type int hence you need to try to use correct format specifier ie, %d

DECLARE @MaxAmount int = 16;
DECLARE @minAmount int = 1;
Raiserror('Total Amount should be less than %d and Greater than %d',@MaxAmount,@MinAmount)

Check RAISEERROR for details.

Shag answered 16/9, 2015 at 10:11 Comment(1)
This didn't work for me, I had to additionally supply severity and state parameters as per @Edward Comeau's answer and THEN the max/min amount params otherwise the message was: Total Amount should be less than (null) and Greater than (null)Corrigible
B
10

You need to use %I for integers and as mentioned, declare the variables before use.

declare @MaxAmount int, @MinAmount int
select @MaxAmount = 50, @MinAmount = 5
Raiserror('Total Amount should be less than %i and Greater than %i',16,1,@MaxAmount,@MinAmount)
Bethea answered 16/9, 2015 at 10:10 Comment(0)
D
1

I think you try in this way:

DECLARE @MaxAmount int = 16;
DECLARE @MinAmount int = 1;

Raiserror('Total Amount should be less than %d and Greater than %d',@MaxAmount,@MinAmount)

If you want further information about RAISERROR, go here

Daye answered 16/9, 2015 at 10:10 Comment(0)
S
1

The above solutions did not work for me, because you have to declare also severity and state. Without it the result will be like this:

Total Amount should be less than (null) and Greater than (null)

You can try this:

DECLARE @MaxAmount int = 16;
DECLARE @MinAmount int = 1;

Raiserror('Total Amount should be less than %d and Greater than %d', 16, 1, @MaxAmount, @MinAmount)
Scheffler answered 1/6, 2020 at 7:14 Comment(1)
I appreciate you acknowledging the previous answers and highlighting how your answer differs from them. That’s especially useful when responding to old questions with established answers, as in this case. That said, @Edward-Comeau’s answer from five years ago does include severity and state.Psychoanalysis

© 2022 - 2024 — McMap. All rights reserved.