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

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

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

问题

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

Declare @DO_BIG_UPDATE Int = 0;

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

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

这是 SQL Server Management Studio 18.8。

英文:

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

Declare @DO_BIG_UPDATE Int = 0;

How do I do that with table variables??

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

This is SQL Server Management Studio 18.8

答案1

得分: 3

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

所以你需要两个语句:

declare @USERS table (
	Id int identity primary key, 
	[Status] int not null, 
	LoginId varchar(64) not null);

insert into @USERS values
	(1, 1, 'asdf'),
	(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:

declare @USERS table (
	Id int identity primary key, 
	[Status] int not null, 
	LoginId varchar(64) not null);

insert into @USERS values
	(1, 1, 'asdf'),
	(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:

确定