hello friend, your query is very good and the problem I found that if you have more than one column in the relationship of error there. follows a version I wrote that le all columns.
declare @criavarchar(max)
select @nomeTabela = 'nametable'
if object_id('tempdb..#tmp') is not null
drop table #tmp
select o2.name ,
'[' + SCHEMA_NAME(o1.schema_id) + '].[' + o1.name + ']' as Referencing_Object_name
, s.name as Constraint_name
, c1.name as referencing_column_Name
, '[' + SCHEMA_NAME(o2.schema_id) + '].[' + o2.name + ']' as Referenced_Object_name
, c2.name as Referenced_Column_Name
, fk.keyno as orderKey
, '[' + SCHEMA_NAME(o1.schema_id) + '].[' + s.name + ']' Constraint_name_schema
into #tmp
from sysforeignkeys fk
inner join sys.objects o1 on fk.fkeyid = o1.object_id
inner join sys.objects o2 on fk.rkeyid = o2.object_id
inner join sys.columns c1 on c1.object_id = o1.object_id and c1.column_id = fk.fkey
inner join sys.columns c2 on c2.object_id = o2.object_id and c2.column_id = fk.rkey
inner join sys.objects s on fk.constid = s.object_id
and o2.name=@nomeTabela -- this predicate for a specific table
order by 1, fk.keyno
select @drop = (
select distinct
'||IF EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'''+ Constraint_name_schema + ''') AND parent_object_id = OBJECT_ID(N''' + Referencing_Object_name + '''))' + '||' +
'ALTER TABLE ' +
Referencing_Object_name +
' DROP CONSTRAINT ' +
Constraint_name
from #tmp o1 FOR XML PATH('')
)
select @cria = (
select distinct
'||ALTER TABLE ' +
Referencing_Object_name +
' WITH NOCHECK ADD CONSTRAINT ' +
Constraint_name +
' FOREIGN KEY ' +
'(' +
STUFF(( SELECT
'],[' + c1.referencing_column_Name
FROM #tmp c1
where c1.Referencing_Object_name = o1.Referencing_Object_name
group by c1.referencing_column_Name,orderKey
order by orderKey
FOR XML PATH('')
), 1, 2, '') + ']'
+ ')' + '||' +
' REFERENCES ' +
Referenced_Object_name +
'(' +
STUFF(( SELECT
'],[' + c1.Referenced_Column_Name
FROM #tmp c1
where c1.Referenced_Object_name = o1.Referenced_Object_name
group by c1.Referenced_Column_Name,orderKey
order by orderKey
FOR XML PATH('')
), 1, 2, '') + ']'
+ ')'
from #tmp o1 FOR XML PATH('') )
set @cria = replace(@cria,'||',char(13) + char(10))
set @drop = replace(@drop,'||',char(13) + char(10))
print (@drop)
print (@cria)