Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use variables in SQL raiserror

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".

like image 795
Nuke Avatar asked Sep 16 '15 10:09

Nuke


People also ask

Can I use variables in SQL query?

You can use variable objects in an SQL query as well as string values.

How do you input a variable in SQL?

The syntax for assigning a value to a SQL variable within a SELECT query is @ var_name := value , where var_name is the variable name and value is a value that you're retrieving. The variable may be used in subsequent queries wherever an expression is allowed, such as in a WHERE clause or in an INSERT statement.

What does Raiserror do in SQL?

RAISERROR is a SQL Server error handling statement that generates an error message and initiates error processing. RAISERROR can either reference a user-defined message that is stored in the sys. messages catalog view or it can build a message dynamically.

How do I print a value in SQL?

Declare @SumVal int; Select @SumVal=Sum(Amount) From Expense; Print @SumVal; You can, of course, print any number of fields from the table in this way. Of course, if you want to print all of the results from a query that returns multiple rows, you'd just direct your output appropriately (e.g. to Text).


2 Answers

%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.

like image 185
Rahul Tripathi Avatar answered Sep 20 '22 20:09

Rahul Tripathi


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)
like image 35
Edward Comeau Avatar answered Sep 21 '22 20:09

Edward Comeau