刪除表字段的sql語句
哎,還是上週的事情了,csdn的部落格最近咋老是打不開呢!
基本語句:Alter table 表名 drop Column 欄位名
另單單是這樣是不行滴,還要刪除對應的關係滴。下面就把查詢到的那篇文章引用下吧!
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: lw
-- Create date: 2009-07-31
-- Description: 強行刪除表列,【無錯誤】【刪除表的列之前一定要刪除依賴,索引】,不然會報很多錯誤
-- =============================================
alter PROCEDURE [dbo].[Delete_Column_Constraint]
(
@tablename nvarchar(50),
@columnname nvarchar(50)
)
AS
--刪除某欄位的所有關係
declare tb cursor local for
--預設值約束
select sql='alter table ['+b.name+'] drop constraint ['+d.name+']'
from syscolumns a
join sysobjects b on a.id=b.id
join syscomments c on a.cdefault=c.id
join sysobjects d on c.id=d.id
where b.name = @tablename
and a.name = @columnname
union all --外來鍵引用
select s='alter table ['+c.name+'] drop constraint ['+b.name+']'
from sysforeignkeys a
join sysobjects b on b.id=a.constid
join sysobjects c on c.id=a.fkeyid
join syscolumns d on d.id=c.id and a.fkey=d.colid
join sysobjects e on e.id=a.rkeyid
join syscolumns f on f.id=e.id and a.rkey=f.colid
where e.name = @tablename
and d.name = @columnname
union all --索引
select case e.xtype when 'PK' then 'alter table ['+c.name+'] drop constraint ['+e.name+']'
else 'drop index ['+c.name+'].['+a.name+']' end
from sysindexes a
join sysindexkeys b on a.id=b.id and a.indid=b.indid
join sysobjects c on b.id=c.id and c.xtype='U' and c.name<>'dtproperties'
join syscolumns d on b.id=d.id and b.colid=d.colid
join sysobjects e on c.id=e.parent_obj
where a.indid not in(0,255)
and c.name='a'
and d.name='id'
declare @s varchar(8000)
open tb
fetch next from tb into @s
while @@fetch_status=0
begin
exec(@s)
fetch next from tb into @s
end
close tb
deallocate tb
DECLARE @SQL AS nvarchar(500)
set @SQL = 'Alter table ' + @tablename + ' Drop Column ' + @columnname
EXECUTE sp_executesql @SQL
GO