T-SQL table and other variables in one DECLARE block

Failed to compile the following:

  DECLARE
    @DateFrom Date = '20151225',
    @DateTo Date = '20151226',
    @Ids TABLE (Id Int NOT NULL);

with an error:

Incorrect syntax next to the keyword "TABLE".

But when I add my own DECLAREto declare a table variable, it compiles fine:

 DECLARE
    @DateFrom Date = '20151225',
    @DateTo Date = '20151226';

 DECLARE
    @Ids TABLE (Id Int NOT NULL);

Here is the SQL script.

What is wrong with the first fragment? Are we not allowed to declare table variables that share the same block DECLAREwith other variable declarations?

+4
source share
2 answers

From the DECLAREdocumentation :

, DECLARE.

:

DECLARE 
{ 
    { @local_variable [AS] data_type  | [ = value ] }
  | { @cursor_variable_name CURSOR }
} [,...n] 
| { @table_variable_name [AS] <table_type_definition> } 

@local_variable ( [,...n]) @table_variable_name.

+8

, , .

CREATE TYPE dbo.ids as TABLE(Id Int NOT NULL)

DECLARE
    @DateFrom Date = '20151225',
    @DateTo Date = '20151226',
    @Ids dbo.ids;

. Table type FUNCTION/STORED PROCEDURE, READONLY

+3

Source: https://habr.com/ru/post/1621744/


All Articles