简体   繁体   English

T-SQL表和一个DECLARE块中的其他变量

[英]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'. 关键字“TABLE”附近的语法不正确。

But when I add its own DECLARE for the table variable declaration, it compiles perfectly: 但是当我为表变量声明添加自己的DECLARE ,它完美地编译:

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

 DECLARE
    @Ids TABLE (Id Int NOT NULL);

Here is the SQL fiddle. 是SQL小提琴。

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? 我们不允许声明与其他变量声明共享相同DECLARE块的表变量?

From the DECLARE documentation : DECLARE文档

When declaring table variables, the table variable must be the only variable being declared in the DECLARE statement. 声明表变量时,表变量必须是DECLARE语句中声明的唯一变量。

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 . 可以声明一个或多个@local_variable[,...n]部分),或只声明一个@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 注意:如果使用Table type作为FUNCTION/STORED PROCEDURE 输入参数 ,则需要将其声明为READONLY

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM