天天看點

sql添加、删除表中的列

添加沒有預設值:alter table Test add BazaarType char(1)

有預設值的添加列:alter table Test add BazaarType char(1) default(0)

删除沒有預設值的列:alter table Test drop COLUMN BazaarType

删除有預設值的列:先删除限制(預設值)alter table Test DROP CONSTRAINT DF__Test__BazaarType__3C4ACB5F,然後在删除列

alter table Test DROP COLUMN BazaarType

系統自帶的查詢限制條件的存儲過程:exec sp_helpconstraint 表名

添加字段:

允許空字元: alter table 表名 add 新字段 字段類型 NULL

不允許空字元: alter table 表名 add 新字段 字段類型 not NULL

增加字段

alter table docdsp add dspcode char(200)

删除字段

ALTER TABLE table_NAME DROP COLUMN column_NAME

修改字段類型

ALTER TABLE table_name ALTER COLUMN column_name new_data_type

改名

sp_rename

更改目前資料庫中使用者建立對象(如表、列或使用者定義資料類型)的名稱。

文法

sp_rename [ @objname = ] 'object_name' ,

    [ @newname = ] 'new_name'

    [ , [ @objtype = ] 'object_type' ]

--假設要處理的表名為: tb

--判斷要添加列的表中是否有主鍵

if exists(select 1 from sysobjects where parent_obj=object_id('tb') and xtype='PK')

begin

print '表中已經有主鍵,列隻能做為普通列添加'

--添加int類型的列,預設值為0

alter table tb add 列名 int default 0

end

else

begin

print '表中無主鍵,添加主鍵列'

--添加int類型的列,預設值為0

alter table tb add 列名 int primary key default 0

end