Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

T-SQL Table and other variables in one DECLARE block

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?

like image 804
Alexander Abakumov Avatar asked Dec 25 '15 22:12

Alexander Abakumov


2 Answers

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_variables can be declared (the [,...n] part), or only one @table_variable_name.

like image 70
Jakub Lortz Avatar answered Oct 10 '22 03:10

Jakub Lortz


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

like image 25
Pரதீப் Avatar answered Oct 10 '22 02:10

Pரதீப்