声明并初始化一个表变量在一条语句中

huangapple go评论89阅读模式
英文:

Declare *and* initialize a table variable in a single statement

问题

我可以在同一语句中声明和初始化简单的变量:

  1. Declare @DO_BIG_UPDATE Int = 0;

如何在表变量中进行这样的操作?

  1. Declare @USERS table (Id Int identity primary key, Status Int Not Null, LoginId VarChar(64) Not Null) = (
  2. 1, 1, 'asdf',
  3. 2, 2, 'asdf'
  4. );

这是 SQL Server Management Studio 18.8。

英文:

I can declare and initialize simple variables in the same statement:

  1. Declare @DO_BIG_UPDATE Int = 0;

How do I do that with table variables??

  1. Declare @USERS table (Id Int identity primary key, Status Int Not Null, LoginId VarChar(64) Not Null) = (
  2. 1,1,'asdf',
  3. 2,2,'asdf'
  4. );

This is SQL Server Management Studio 18.8

答案1

得分: 3

抱歉,但不可以这样做。这不是声明表变量的有效语法(截至 SQL Server 2022)。

所以你需要两个语句:

  1. declare @USERS table (
  2. Id int identity primary key,
  3. [Status] int not null,
  4. LoginId varchar(64) not null);
  5. insert into @USERS values
  6. (1, 1, 'asdf'),
  7. (2, 2, 'asdf');
英文:

Sorry, but no you cannot do that. It is not valid syntax for declaring table variables (as of SQL Server 2022).

https://learn.microsoft.com/en-us/sql/t-sql/language-elements/declare-local-variable-transact-sql

So you will need two statements:

  1. declare @USERS table (
  2. Id int identity primary key,
  3. [Status] int not null,
  4. LoginId varchar(64) not null);
  5. insert into @USERS values
  6. (1, 1, 'asdf'),
  7. (2, 2, 'asdf');

huangapple
  • 本文由 发表于 2023年5月15日 09:08:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/76250316.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定