Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot assign a default value to a local variable in SQL

Tags:

I am trying to declare local variable like:

DECLARE @thresholdDate DATETIME = '2014-11-30' 

And I am getting error:

Cannot assign a default value to a local variable.

As per documentation:

DECLARE @find varchar(30);  /* Also allowed:  DECLARE @find varchar(30) = 'Man%';  */ 

What I am doing wrong?

like image 561
Vladimirs Avatar asked Nov 21 '14 11:11

Vladimirs


People also ask

How do you assign a value to a local variable in SQL?

To assign a value to a variable, use the SET statement. This is the preferred method of assigning a value to a variable. A variable can also have a value assigned by being referenced in the select list of a SELECT statement.

Is it possible to use default value of local variables?

No, local variables do not have default values. Once we create a local variable we must initialize it before using it. Since the local variables in Java are stored in stack in JVM there is a chance of getting the previous value as default value. Therefore, In Java default values for local variables are not allowed.

How do you declare a variable with default value?

To provide a default value for a variable, include a DEFAULT clause. The value can be specified as an expression; it need not be a constant. If the DEFAULT clause is missing, the initial value is NULL. When a variable is first declared, its value is set to NULL.

What is the default value of local?

There is no default value for local variables, so local variables should be declared and an initial value should be assigned before the first use.


1 Answers

Prior to SQL Server 2008, assigning a default value (or initial value) to a local variable is not allowed; otherwise this error message will be encountered.

Solution 1: (Use SET)

DECLARE @thresholdDate DATETIME  set @thresholdDate = '2014-11-30' 

For more details about the error : http://www.sql-server-helper.com/error-messages/msg-139.aspx

Solution 2: (Upgrade)

Another way of avoiding this error, which is a little bit a far-fetched solution, is to upgrade to SQL Server 2008. SQL Server 2008 now allows the assigning of a value to a variable in the DECLARE statement.

like image 101
Veera Avatar answered Sep 29 '22 05:09

Veera