Technical Article

Generate Create / Drop Scripts for the Foreign Key

,

This Function and the query will generate the script for Create / Drop/ Create Constraint based on a Naming Convention . More changes can be done on this. This is very simple

/*
Purpose : To get the Column name for a specified table id and the column id
Author: Jeswanth
*/Create Function Column_Name(@tableid int,@ColumnID smallint) 
returns Varchar(4000)
as
begin
declare @column_name varchar(4000)
select @column_name = name from sysColumns where id = @tableid and colid=@ColumnID
return @column_name
end

----Now Query the Sysreferences or sysforeignkeys table using this function to generate the scripts

select 'ALTER TABLE [dbo].[' + object_name(fkeyid) + ']'+ ' ADD CONSTRAINT [' + object_name(constid) + '] FOREIGN KEY (['+ dbo.Column_Name(fkeyid,fkey) + '])REFERENCES [dbo].[' + object_name(rkeyid) + '](['+ dbo.Column_name(rkeyid,rkey)  + '])' from sysforeignkeys


select 'ALTER TABLE [dbo].[' + object_name(fkeyid) + ']'+ ' DROP CONSTRAINT [' + object_name(constid) + ']'   from sysforeignkeys

Rate

You rated this post out of 5. Change rating

Share

Share

Rate

You rated this post out of 5. Change rating