开发者

IDENTITY NOT NULL at Table Creation

开发者 https://www.devze.com 2023-03-09 14:11 出处:网络
Can anyone please tell me whether the instruction IDENTITY NOT NULL at a table creation is redundant or not? I mean, judging by the message

Can anyone please tell me whether the instruction IDENTITY NOT NULL at a table creation is redundant or not? I mean, judging by the message

DEFAULT or NULL are not allowed as explicit identity values.

I would s开发者_开发知识库ay that any column declared as IDENTITY is implicitly also declared as NOT NULL, but I would like to make sure. Can anyone please confirm?

Thank you very much.


SQL Server adds NOT NULL constraint to identity columns automatically eventhough he did not speficy it when creating a table

Consider the following table script

create table test(id int identity(1,1), name varchar(1000))

Now Generate the script of the table from Management Studio. It generates the script as

CREATE TABLE [dbo].[test](
    [id] [int] IDENTITY(1,1) NOT NULL,
    [name] [varchar](1000) NULL
) ON [PRIMARY]

Eventhough NOT NULL constraint is not specified in the table script by default it is added. The identity column will never be NULL. So NOT NULL constraint is added default


SQL Server (2008, and probably earlier versions as well) will not allow you to create an identity column on a NULL column. Try it:

CREATE TABLE Foo1
 (
   FooId  int  identity not null
  ,Data  varchar(20)  not null
 )

works, where

CREATE TABLE Foo2
 (
   FooId  int  identity null
  ,Data  varchar(20)  not null
 )

generates error message Could not create IDENTITY attribute on nullable column 'FooId', table 'Foo2'.

0

精彩评论

暂无评论...
验证码 换一张
取 消