SQL Server: Add column with default value and description in T-SQL

假设我要在表 dbo.tblBinaryCommand 中添加一个新字段 ProtocolId,并且在添加字段的时候指定数据类型为 bigint,不允许为空,默认值为 -1,我还想给这个字段加一段Description,如下:

Message protocol id refer to Protocol definition table tblProtocol column ProtocolId.

Notes:
(1) avaliable value should be greater then 0.
(2) -1 means NULL.

就是下面这个截图:

SQL Server: Add column with default value and description in T-SQL_第1张图片


这个操作,用 T-SQL 来实现,是这样的:


-- Add column ProtocolId in table tblBinaryCommand
if not exists 
(
	select column_name from INFORMATION_SCHEMA.columns where table_name = 'tblBinaryCommand' and column_name = 'ProtocolId'
)
Begin
	ALTER TABLE dbo.tblBinaryCommand 
	ADD ProtocolId bigint NOT NULL 
	CONSTRAINT DF_tblBinaryCommand_ProtocolId DEFAULT -1;

	EXEC sys.sp_addextendedproperty 
		@name = N'MS_Description',
		@value = 
		
N'Message protocol id refer to Protocol definition table tblProtocol column ProtocolId.

Notes:
(1) avaliable value should be greater then 0.
(2) -1 means NULL.',
		@level0type = N'SCHEMA',
		@level0name = N'dbo',
		@level1type = N'TABLE',
		@level1name = N'tblBinaryCommand',
		@level2type = N'COLUMN',
		@level2name = N'ProtocolId';
End;


Notes:

(1) 这段SQL脚本可以重复执行多次,如果段 ProtocolId 已经存在则不作任何操作。这个在 if not exists (...) 这个判断里面。

(2) 字段的默认值是通过添加一个约束 CONSTRAINT DF_tblBinaryCommand_ProtocolId DEFAULT -1 来实现的。

(3) 给字段添加描述信息(Description)是通过调用存储过程 sys.sp_addextendedproperty 来实现的。




你可能感兴趣的:(sql,server,schema,脚本,table,null,存储)