Delete the foreign key referenced by a table field, save it, and re-Add the previously deleted foreign key after data import.

Source: Internet
Author: User
Create   Procedure Genforeignkey
@ Tablename   Varchar ( 200 ) -- Name of the table in the foreign key database to be added
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 Primary Key column 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)
, Foreign key column ID = B. fkey
, VF = ( Select Name From Syscolumns Where Colid = B. fkey And ID = B. fkeyid)
From Sysobjects
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
)
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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.