alter table Student
add fee
int
not null
default 15
alter table Student
alter column S_Sex
varchar(10) null
with t as (select * from Student)
select * from t
alter table Student
add C_S_Id int null
alter table Student
add constraint C_S_Id
foreign key (C_S_Id)
references Course(C_Id)
go
select name
from sys.foreign_key_columns f
inner join sys.objects o on f.constraint_object_id=o.object_id
where f.parent_object_id=object_id('Student')
alter table Course drop constraint FK__Course__Stu_Id__15502E78
sp_helpdb Test
sp_helpdb
sp_help Course
sp_help
ALTER DATABASE Test
SET COMPATIBILITY_LEVEL = 80||90||100
GO
SET IDENTITY_INSERT Student on
go
SET IDENTITY_INSERT Student off
go
SET NOCOUNT ON
SET QUOTED_IDENTIFIER ON
SET ANSI_NULLS ON
ALTER TABLE Student
ADD CONSTRAINT UQ_CourseID_Primary_Key
UNIQUE (C_Id)
ALTER TABLE Student
ADD CONSTRAINT DF_S_Name_Default
DEFAULT('233') FOR S_Name
ALTER TABLE Student
ADD CONSTRAINT FK_C_Id_Foreign_Key
FOREIGN KEY (C_Id)
REFERENCES Course(C_Id)
ON UPDATE CASCADE
ON DELETE CASCADE
补充一个添加和删除主键约束和查询指定表的主外键约束名的 sql 语句:
alter table Student
add constraint S_C_Id
primary key (S_Id)
select a.Name as 表名,b.Xtype as 键类型,b.Name as 键名
from sysobjects a,sysobjects b
where a.ID=b.parent_obj and a.name='Student'
and b.Xtype in('F','PK')
alter table Student
drop constraint PK__Student__A3DFF08D170CE4CD
使用 sql 系统存储过程(sp_helpconstraint)根据指定表的表名查询表中的约束。
为指定表添加主键约束,但显式设置为非聚集索引。
exec sp_helpconstraint UserInfo
alter table UserInfo drop constraint PK__UserInfo__5A2040BBA6D6767A
SELECT *
FROM sys.default_constraints a
LEFT JOIN sys.sysconstraints b ON a.object_id = b.constid AND a.parent_object_id=b.id
LEFT JOIN sys.columns c ON a.object_id = c.default_object_id
WHERE a.parent_object_id = OBJECT_ID('Student')
AND c.NAME='Flag'
ALTER TABLE Student DROP constraint DF__Stu__Flag__707E9C7C