SQL Server DEFAULT Constraints
如果一个表某一字段,设置了Default(默认)约束,那可以在插入记录时,没有为此字段指定值,那系统就取默认值为数据来填充此字段。
在创建表时,可以定义此Default约束:
代码
CREATE TABLE [dbo].[Gallery]
(
[GalleryId] [int] IDENTITY(1,1) PRIMARY KEY NOT NULL,
[Subject] [nvarchar](50) NOT NULL,
[Description] [nvarchar](100) NULL,
[Directory] [nvarchar](150) NULL,
[Picture] [image] NULL,
[Hits] [int] NOT NULL,
[CreateDate] [datetime] DEFAULT(CURRENT_TIMESTAMP) NOT NULL --在记录插入时,把当前系统时间插入
)
(
[GalleryId] [int] IDENTITY(1,1) PRIMARY KEY NOT NULL,
[Subject] [nvarchar](50) NOT NULL,
[Description] [nvarchar](100) NULL,
[Directory] [nvarchar](150) NULL,
[Picture] [image] NULL,
[Hits] [int] NOT NULL,
[CreateDate] [datetime] DEFAULT(CURRENT_TIMESTAMP) NOT NULL --在记录插入时,把当前系统时间插入
)
如果是对已经创的表,可以用ALTER来修改,为字段定义一个DEFAULT默认约束。
ALTER TABLE [dbo].[Gallery]
ADD CONSTRAINT [DF_Gallery_CreateDate]
DEFAULT (CURRENT_TIMESTAMP) FOR [CreateDate]
ADD CONSTRAINT [DF_Gallery_CreateDate]
DEFAULT (CURRENT_TIMESTAMP) FOR [CreateDate]
删除字段默认(Default)约束:
ALTER TABLE [dbo].[Gallery]
ALTER COLUMN [CreateDate] DROP DEFAULT
ALTER COLUMN [CreateDate] DROP DEFAULT