--判断要添加列的表中是否有主键
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
/**************************************************************************************/
判断tablename中是否存在name字段
if exists(select * from syscolumns where id=object_id('tablename') and name='name') begin
select * from tablename;
end
判断tablename中是否存在name字段且删除字段
if exists(select * from syscolumns where id=object_id('tablename') and name='name') begin
select * from people;
alter table tablename DROP COLUMN name
end
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
/**************************************************************************************/
判断tablename中是否存在name字段
if exists(select * from syscolumns where id=object_id('tablename') and name='name') begin
select * from tablename;
end
判断tablename中是否存在name字段且删除字段
if exists(select * from syscolumns where id=object_id('tablename') and name='name') begin
select * from people;
alter table tablename DROP COLUMN name
end