SQL Server: creating table variable, error in primary key constraint definition

后端 未结 4 1051
遇见更好的自我
遇见更好的自我 2021-01-27 14:47

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 wo         


        
4条回答
  •  轮回少年
    2021-01-27 14:59

    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)
    )
    

提交回复
热议问题