The following fails to compile:
DECLARE
@DateFrom Date = '20151225',
@DateTo Date = '20151226',
@Ids TABLE (Id Int NOT NULL);
with the error:
Incorrect syntax near the keyword 'TABLE'.
But when I add its own DECLARE
for the table variable declaration, it compiles perfectly:
DECLARE
@DateFrom Date = '20151225',
@DateTo Date = '20151226';
DECLARE
@Ids TABLE (Id Int NOT NULL);
Here is the SQL fiddle.
What is wrong with the first snippet? We aren't allowed to declare a table variables sharing the same DECLARE
block with other variable declarations?
From the DECLARE
documentation:
When declaring table variables, the table variable must be the only variable being declared in the DECLARE statement.
You can see it clearly in the syntax too:
DECLARE
{
{ @local_variable [AS] data_type | [ = value ] }
| { @cursor_variable_name CURSOR }
} [,...n]
| { @table_variable_name [AS] <table_type_definition> }
One or more @local_variable
s can be declared (the [,...n]
part), or only one @table_variable_name
.
In case if you want first snippet to work, Create table types.
CREATE TYPE dbo.ids as TABLE(Id Int NOT NULL)
DECLARE
@DateFrom Date = '20151225',
@DateTo Date = '20151226',
@Ids dbo.ids;
Note: If you use Table type
as input parameter to FUNCTION/STORED PROCEDURE
you need to declare it as READONLY
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