17 May 2010

Cerca campi orfani fra due tabelle

create procedure sys_CampiOrfani_sp
	@tab1 as nvarchar(100), 
	@tab2 as nvarchar(100)
AS
BEGIN
	set nocount on

	select	c.*, s.name as typeName
	into	#aaa
	from	sys.columns c inner join sys.types s on 
			c.system_type_id = s.system_type_id
	where	c.object_id = object_id(@tab1)


	select	c.*, s.name as typeName
	into	#bbb
	from	sys.columns c inner join sys.types s on 
			c.system_type_id = s.system_type_id
	where	c.object_id = object_id(@tab2)


	select	@tab1 AS 'Table name', a.name AS 'Nome campo', a.typeName, 
			a.max_length, a.precision, a.scale
	from	#aaa a LEFT join #bbb b on 
			a.name = b.name
	where	b.name is null
	order by
			a.name


	select	@tab2 AS 'Table name', b.name AS 'Nome campo', b.typeName, 
			b.max_length, b.precision, b.scale
	from	#aaa a RIGHT join #bbb b on 
			a.name = b.name
	where	a.name is null
	order by
			b.name

END

go

exec sys_CampiOrfani_sp 
'MPS_InterventiStorico',
'RichiesteManutenzione_tb'

if object_id('sys_CampiOrfani_sp') is not null 
	drop procedure sys_CampiOrfani_sp