SQLSERVER实现更改表名,更改列名,更改约束代码
废话不多说了,具体详情如下所示:
1.修改表名
格式:sp_renametablename,newtablename
sp_renametablename,newtablename
2.修改字段名
格式:sp_rename'tablename.colname',newcolname,'column'
sp_rename'tablename.colname',newcolname,'column'
3.添加字段
格式:altertabletable_nameaddnew_columndata_type[interality_codition]
示例1
ALTERTABLEstudentAddnationalityvarchar(20)
--示例2添加int类型的列,默认值为0
altertablestudentaddstudentNameintdefault0--示例3添加int类型的列,默认值为0,主键 altertablestudentaddstudentIdintprimarykeydefault0--示例4判断student中是否存在name字段且删除字段 ifexists(select*fromsyscolumnswhereid=object_id('student')andname='name')begin altertablestudentDROPCOLUMNname end
4.更改字段
格式:altertabletable_namealtercolumncolumn_name
ALTERTABLEstudentALTERCOLUMNnameVARCHAR(200)
5.删除字段
格式:altertabletable_namedropcolumncolumn_name
ALTERTABLEstudentDROPCOLUMNnationality;
6.查看字段约束
格式:select*frominformation_schema.constraint_column_usagewhereTABLE_NAME=table_name
SELECTTABLE_NAME,COLUMN_NAME,CONSTRAINT_NAMEFROMinformation_schema.CONSTRAINT_COLUMN_USAGE WHERETABLE_NAME='student'
7.查看字段缺省约束表达式(即默认值等)
格式:select*frominformation_schema.columnswhereTABLE_NAME=table_name
SELECTTABLE_NAME,COLUMN_NAME,COLUMN_DEFAULTFROMinformation_schema.COLUMNS WHERETABLE_NAME='student'
8.查看字段缺省约束名
格式:selectnamefromsysobjectswhereobject_id(table_name)=parent_objandxtype='D'
selectnamefromsysobjects whereobject_id('表?名?')=parent_objandxtype='D'
9.删除字段约束
格式:altertabletablenamedropconstraintconstraintname
ALTERTABLEstudentDROPCONSTRAINTPK__student__2F36BC5B772B9A0B
10.添加字段约束
格式:altertabletablenameaddconstraintconstraintnameprimarykey(column_name)
--示例1
ALTERTABLEstuInfoADDCONSTRAINTPK_stuNoPRIMARYKEY(stuNo)--示例2添加主键约束(PrimaryKey) --存在主键约束PK_stuNO,则删除 IFEXISTS(SELECT*FROMsysobjectsWHEREname='PK_stuNo'andxtype='PK') AlterTABLEstuInfo DropConstraintPK_stuNo Go--重新添加主键约束PK_stuNO ALTERTABLEstuInfoADDCONSTRAINTPK_stuNoPRIMARYKEY(stuNo) Go--示例3添加唯一UQ约束(UniqueConstraint) --存在唯一约束UQ_stuNO,则删除 IFEXISTS(SELECT*FROMsysobjectsWHEREname='UQ_stuID'andxtype='UQ') AlterTABLEstuInfo DropConstraintUQ_stuID Go --重新添加唯一约束UQ_stuID ALTERTABLEstuInfoADDCONSTRAINTUQ_stuIDUNIQUE(stuID)--示例4添加默认DF约束(DefaultConstraint) --存在默认约束UQ_stuNO,则删除 IFEXISTS(SELECT*FROMsysobjectsWHEREname='DF_stuAddress'andxtype='D') AlterTABLEstuInfoDropConstraintDF_stuAddress Go--重新添加默认约束DF_stuAddress ALTERTABLEstuInfoADDCONSTRAINTDF_stuAddressDEFAULT('地址不详')FORstuAddress--示例5检查CK约束(CheckConstraint) --存在检查约束UQ_stuNO,则删除 IFEXISTS(SELECT*FROMsysobjectsWHEREname='CK_stuAge'andxtype='C') AlterTABLEstuInfoDropCons
以上所述是小编给大家介绍的SQLSERVER实现更改表名,更改列名,更改约束代码,希望对大家有所帮助!