删除一个表字段所引用的外键,并保存下来,在数据导入后再重新加入先前删除的外键
CREATE PROCEDURE GenForeignKey
@tablename varchar(200) --将要加上外键数据库里的表名
as
declare @cur cursor
declare @fk varchar(100)
declare @execsql varchar(8000)
begin
Declare @SQL varchar(8000)
SET @SQL=''
select @SQL = @SQL
+char(13)+' alter table '+a.VT
+ ' add constraint FK_'+VT+'_'+VF+'_'+VR+'_'+VP+
' foreign key('+VF+')
references '+VR+'('+VP+')'
FROM
(
SELECT 主键列ID=b.rkey
,VP=(SELECT name FROM syscolumns WHERE colid=b.rkey AND id=b.rkeyid)
,VT=object_name(b.fkeyid)
,VR=object_name(b.rkeyid)
,外键列ID=b.fkey
,VF=(SELECT name FROM syscolumns WHERE colid=b.fkey AND id=b.fkeyid)
FROM sysobjects a
join sysforeignkeys b on a.id=b.constid
join sysobjects c on a.parent_obj=c.id
where a.xtype='f' AND c.xtype='U'
and object_name(b.fkeyid)= @tablename
) a
print @sql
set @cur = CURSOR READ_ONLY
for
select so.name
from sysforeignkeys sf
join sysobjects so on sf.constid=so.id
join sysobjects so1 on sf.fkeyid=so1.id
where so1.name=@tablename
open @cur
FETCH NEXT FROM @cur INTO @fk
while (@@FETCH_STATUS = 0)
begin
set @execsql = 'ALTER TABLE '+@tablename+' drop CONSTRAINT ' + @fk
exec(@execsql)
FETCH NEXT FROM @cur INTO @fk
end
close @cur
deallocate @cur
end
GO
@tablename varchar(200) --将要加上外键数据库里的表名
as
declare @cur cursor
declare @fk varchar(100)
declare @execsql varchar(8000)
begin
Declare @SQL varchar(8000)
SET @SQL=''
select @SQL = @SQL
+char(13)+' alter table '+a.VT
+ ' add constraint FK_'+VT+'_'+VF+'_'+VR+'_'+VP+
' foreign key('+VF+')
references '+VR+'('+VP+')'
FROM
(
SELECT 主键列ID=b.rkey
,VP=(SELECT name FROM syscolumns WHERE colid=b.rkey AND id=b.rkeyid)
,VT=object_name(b.fkeyid)
,VR=object_name(b.rkeyid)
,外键列ID=b.fkey
,VF=(SELECT name FROM syscolumns WHERE colid=b.fkey AND id=b.fkeyid)
FROM sysobjects a
join sysforeignkeys b on a.id=b.constid
join sysobjects c on a.parent_obj=c.id
where a.xtype='f' AND c.xtype='U'
and object_name(b.fkeyid)= @tablename
) a
print @sql
set @cur = CURSOR READ_ONLY
for
select so.name
from sysforeignkeys sf
join sysobjects so on sf.constid=so.id
join sysobjects so1 on sf.fkeyid=so1.id
where so1.name=@tablename
open @cur
FETCH NEXT FROM @cur INTO @fk
while (@@FETCH_STATUS = 0)
begin
set @execsql = 'ALTER TABLE '+@tablename+' drop CONSTRAINT ' + @fk
exec(@execsql)
FETCH NEXT FROM @cur INTO @fk
end
close @cur
deallocate @cur
end
GO