SqlServer新建表操作DDL
创建新表:
1,五要素
2,not null
3,默认值
4,字段注释,表名称
5,索引
6,指定约束名称
-- ----------------------------
-- Table structure for Table
-- ----------------------------
IF EXISTS (SELECT * FROM sys.all_objects WHERE object_id = OBJECT_ID(N'[dbo].[TableName]') AND type IN ('U'))
DROP TABLE [dbo].[TableName]
CREATE TABLE [dbo].[TableName] (
[CreatedUserID] int DEFAULT ((0)) NOT NULL,
[CreatedTime] datetime DEFAULT (getdate()) NOT NULL,
[ModifiedUserID] int DEFAULT ((0)) NOT NULL,
[ModifiedTime] datetime DEFAULT (getdate()) NOT NULL,
[IsDelete] int DEFAULT ((1)) NOT NULL
)
--指定属性名称
EXEC sp_addextendedproperty
'MS_Description', N'创建人',
'SCHEMA', N'dbo',
'TABLE', N'TableName',
'COLUMN', N'CreatedUserID'
EXEC sp_addextendedproperty
'MS_Description', N'创建时间',
'SCHEMA', N'dbo',
'TABLE', N'TableName',
'COLUMN', N'CreatedTime'
EXEC sp_addextendedproperty
'MS_Description', N'修改人',
'SCHEMA', N'dbo',
'TABLE', N'TableName',
'COLUMN', N'ModifiedUserID'
EXEC sp_addextendedproperty
'MS_Description', N'修改时间',
'SCHEMA', N'dbo',
'TABLE', N'TableName',
'COLUMN', N'ModifiedTime'
EXEC sp_addextendedproperty
'MS_Description', N'是否有效,1:有效,0:无效',
'SCHEMA', N'dbo',
'TABLE', N'TableName',
'COLUMN', N'IsDelete'
EXEC sp_addextendedproperty
'MS_Description', N'表名称',
'SCHEMA', N'dbo',
'TABLE', N'TableName'
--指定默认值(缺省)、指定约束名称(不指定会生成随机名称,不利于维护)
ALTER TABLE [dbo].[tableName] ADD CONSTRAINT [DF_tableName_CreatedUserId] DEFAULT ((0)) FOR [CreatedUserId]
ALTER TABLE [dbo].[tableName] ADD CONSTRAINT [DF_tableName_CreatedTime] DEFAULT (getdate()) FOR [CreatedTime]
ALTER TABLE [dbo].[tableName] ADD CONSTRAINT [DF_tableName_ModifiedUserId] DEFAULT ((0)) FOR [ModifiedUserId]
ALTER TABLE [dbo].[tableName] ADD CONSTRAINT [DF_tableName_ModifiedTime] DEFAULT (getdate()) FOR [ModifiedTime]
ALTER TABLE [dbo].[tableName] ADD CONSTRAINT [DF_tableName_IsDelete] DEFAULT ((1)) FOR [IsDelete]
-- ----------------------------
-- Indexes structure for table Table
-- ----------------------------
CREATE NONCLUSTERED INDEX [IX_Table_xxxID]
ON [dbo].[Table] (
[xxxID] ASC
)
-- ----------------------------
-- Primary Key structure for table Table
-- ----------------------------
ALTER TABLE [dbo].[Table] ADD CONSTRAINT [PK_Table] PRIMARY KEY CLUSTERED ([xxxOOOID])
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON)
ON [PRIMARY]