英文:
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');
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论