--5、删除表
drop table table1;
--6、新建表 field1自增
create table table1
(
field1 int identity(1,1),
field2 varchar(50),
field3 int,
field4 numeric(18,2),
field5 varchar(100)
)
--7、添加不为空限制
alter table table1 alter column field1 int not null;
--8、添加主键
alter table table1 add constraint PK_field1 primary key(field1);
--9获取主键所在列
declare @PKColumn varchar(100);
SELECT @PKColumn=COLUMN_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE TABLE_NAME='table1';
print @PKColumn;
--10删除主键约束
alter table table1 drop constraint PK_field1;
--11、修改类型
alter table table1 alter column field2 int ;
--12、添加默认值
alter table table1 add default(0) for field2 ;
--13、添加列
alter table table1 add field6 varchar(100) not null default('是');
--14、添加默认约束
alter table table1 add default ('是') for field6;
--删除列:因为field6上面有默认约束,所以不能直接删除,需要先删除约束,然后再删除列
--15、先查看当前表中的默认约束有哪些:
select * from sysobjects where xtype='D' and parent_obj=object_id('table1')
--16、删除默认约束
alter table table1drop constraint DF__table1__field6__0425A276
---17、删除列(此时因为field6上面有default约束,所以不能删除)
alter table table1 drop column field6
--外键
create table table2
(
field1 int not null identity(1,1) primary key ,
field2 varchar(50) default('是'),
field3 int,
field4 numeric(18,2),
field5 varchar(100)
)
--18、判断表是否存在
if object_id(N'table1',N'U') is not null
begin
print '表存在';
end
--19、添加外键:在field3上添加外键
alter table table2 add constraint FK_field3
foreign key (field3)
references table1(field1) on update cascade on delete cascade
--20、删除外键约束
alter table table2 drop constraint FK_field3
--21、查看外键约束
select * from sysobjects where xtype='F' and parent_obj=object_id('table2')