SQL Server: creating table variable, error in prim

2020-05-06 12:30发布

I'm trying to create a table variable with primary key. What is the difference between these two statements? Why the first one does not work?

--This does not work
declare @tabvar table (
    rowid int identity(1, 1) not null,
    var1 int null,
        constraint PK_tabvar_rowid primary key clustered (rowid)
)

--This works
declare @tabvar1 table (
    rowid int identity(1, 1) not null primary key clustered,
    var1 int null
)

4条回答
劫难
2楼-- · 2020-05-06 13:01

Looks like this behavior is well documented in BOL. Look at the syntax definitions for DECLARE TABLE Variable vs CREATE TABLE.

查看更多
劫难
3楼-- · 2020-05-06 13:06

When you create a table like:

CREATE TABLE tabvar (
rowid int identity(1, 1) not null,
var1 int null
   , constraint PK_tabvar_rowid primary key clustered (rowid))

you create a separate SQL object called PK_tabvar_rowid.

This method is preferred for permanent tables as above, because you specifically name the constraint and it exists independently from the table object.

You CAN use the form:

 CREATE TABLE tabvar (
rowid int identity(1, 1) not null primary key,
var1 int null)

but this creates a randomly named constraint, which makes future management more difficult.

For table variables (which are transient) - you CANNOT have an independent constraint - so you MUST use the inline primary key definition.

查看更多
Summer. ? 凉城
4楼-- · 2020-05-06 13:12

There are differences in the syntax between the CREATE TABLE (Transact-SQL) and DECLARE @local_variable (Transact-SQL) used in creating table variables. You can not use the syntax of the first statement to create a variable table.

查看更多
干净又极端
5楼-- · 2020-05-06 13:18

The syntax you're using is for CREATE TABLE, not table variables.

CREATE TABLE tabvar (
    rowid int identity(1, 1) not null,
    var1 int null
       , constraint PK_tabvar_rowid primary key clustered (rowid)
)

The above works fine, as expected. However if you look at the syntax for declaring table variables you'll see what you can and can't do:

declare @tabvar table (
    rowid int identity(1, 1) not null,
    var1 int null,
       primary key (rowid)
)
查看更多
登录 后发表回答