Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I declare a local variable not null?

In T-SQL, I declare a local variable for use with some query like so:

DECLARE @var_last datetime;
SET @var_last = (SELECT TOP(1) col_date FROM tbl_dates ORDER BY col_date);

In an application I'm testing, it would be an error for this query to return NULL, and it's desirable for the query to return a crash error if it were.

I'd like to set @var_last to be NOT NULL but the syntax...

DECLARE @var_last datetime NOT NULL;

...is invalid. I can write a simple check on the return of the query to see if it's NULL, and error if it is, but my question is, is it not possible to declare a local variable as NOT NULL?

like image 797
Mr. Smith Avatar asked Apr 06 '14 22:04

Mr. Smith


People also ask

Can we DECLARE a NOT NULL without an initial value?

No, you can't.

How do you DECLARE a temporary variable in SQL?

Temp variables are created using “DECLARE” statements and are assigned values by using either a SET or SELECT command. This acts like a variable and exists for a particular batch of query executions. It gets dropped once it comes out of batch. Temp variables are also created in the tempdb database but not the memory.

Can you DECLARE variables in a table valued function?

Table-valued parameters allow sending multiple values to functions. Declare a variable as a table-valued parameter and populate it with multiple parameter values. Execute the function.

How do you DECLARE a variable NULL in SQL?

The rule for assigning NULL values to variables or table columns is simple: Use keyword "NULL" directly as normal values. Specificly, "NULL" can be used in SET statements to assign NULL values to variables. "NULL" can be used in SET clauses in UPDATE statements.


2 Answers

That's right, according the documentation for the DECLARE @local_variable, available at: http://technet.microsoft.com/en-us/library/ms188927.aspx, it doesn't accept a NULL | NOT NULL parameter -- those are only valid for column definitions.

If you want to stop execution if you return a NULL, then test for NULL and, if it is, RAISERROR; see: http://technet.microsoft.com/en-us/library/ms178592.aspx.

like image 94
JoeNahmias Avatar answered Nov 03 '22 00:11

JoeNahmias


You can do something like this ...

Using ISNULL()

SELECT TOP(1) @var_last = ISNULL(col_date,'19000101') --<-- Some default value
FROM tbl_dates 
ORDER BY col_date;

Using COALESCE()

SELECT TOP(1) @var_last = COALESCE(col_date,'19000101') --<-- Some default value
FROM tbl_dates 
ORDER BY col_date;
like image 34
M.Ali Avatar answered Nov 02 '22 22:11

M.Ali