zl程序教程

您现在的位置是:首页 >  后端

当前栏目

SQL Server 修改表结构(转载)

serverSQL 修改 结构 转载
2023-09-11 14:21:28 时间

SQL Server 修改表结构

本文链接:https://blog.csdn.net/petezh/article/details/81744374

查看指定表结构

exec sp_help Reports

修改表名

exec sp_rename 'Reports','Reports2'

删除数据表

不能删除有外键约束的表。

drop table Reports

表字段

alter table Reports add NewColumn nchar(5) null --新增字段
alter table Reports alter column NewColumn nvarchar(10) --修改字段属性
exec sp_rename 'Reports.NewColumn','OldColumn'--修改字段名
alter table Reports drop column NewColumn --删除列

字段约束

alter table Reports add constraint Name_UQ unique(Name) --新增唯一约束(此非索引)
alter table Reports drop constraint Name_UQ --删除此约束

字段索引

MSSQL默认主键是聚集索引。一个表只能有一个聚集索引(Clustered Index)。

create index NameIndex on Reports(Name) --新增普通索引(非聚集索引)
create unique index Name_UQ  on Reports(Name) --新增唯一索引(非聚集索引)

exec sp_helpindex Reports --查看表的索引
drop index Reports.NameIndex --删除索引

create nonclustered index NameFileIndex on Categories(CategoryName,PictureFile) --创建非聚集索引(组合索引)

当修改表结构时,sql server可能会弹出对话框:

不允许保存更改。您所做的更改要求删除并重新创建以下表。您对无法重新创建的表进行了更改或者启用了“阻止保存要求重新创建表的更改”选项。

解决方案:菜单栏->工具->选项->设计器->表设计器和数据库设计器,右侧面板,取消勾选“阻止保存要求重新创建表的更改”。