在 SqlServer 2000 上执行下列语句出错
- SQL code
drop table student cascade
请问在 SqlServer 2000上实现级联删除该怎么写呢?
------解决方案--------------------
SQL Server 不支持 drop table ... cascade 语句,用户需要自己手动删除那些引用删除表的表。
不过可以通过 sysforeignkeys 系统表和动态语句实现。
- SQL code
create procedure drop_cascade @tabname varchar(256)
as
declare @level int;
set @level=0;
declare @temp table (oid int,lvl int);
insert into @temp values(object_id(@tabname),@level);
while @@rowcount>0
begin
set @[email protected]+1;
insert into @temp
select fkeyid,@level from sysforeignkeys
where rkeyid in (select oid from @temp where [email protected]);
end
declare @sql varchar(8000);
set @sql='';
select @[email protected]+','+quotename(object_schema_name(oid))+'.'+quotename(object_name(oid))
from (select distinct oid,lvl from @temp t
where lvl=(select min(lvl) from @temp where oid=t.oid)) t
order by lvl desc;
set @sql='drop table '+stuff(@sql,1,1,'')+';';
select @sql;
go
exec drop_cascade 'dbo.students';