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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With