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

后端 未结 4 1050
遇见更好的自我
遇见更好的自我 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:56

    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.

提交回复
热议问题