I'm trying to compare the column heading between two tables and have the difference highlighted in a new table.
For example, in the image below, you can see that the only difference in the between the headings between Table A and Table B is header D. I would like to be able to generate a sql script that will catch the differences and place the difference in a column beside or in a row below as shown in the image.
I don't have any usable data to test with, but I think should at least be very close:
DECLARE @table1 nvarchar(128)
DECLARE @table2 nvarchar(128)
SET @table1 = 'Table A'
SET @table2 = 'Table B'
SELECT COALESCE(t1.name, t2.name) AS column_name,
@table1 AS table1,
@table2 AS table2,
CASE WHEN MAX(t1.name) IS NULL THEN 'Yes' ELSE 'No' END AS is_in_table1,
CASE WHEN MAX(t2.name) IS NULL THEN 'Yes' ELSE 'No' END AS is_in_table2
FROM sys.columns t1
FULL OUTER JOIN sys.columns t2 ON t2.name = t1.name
WHERE t1.object_id = OBJECT_ID(@table1) AND
t2.object_id = OBJECT_ID(@table2) AND
(t1.name IS NULL OR t2.name IS NULL)
GROUP BY COALESCE(t1.name, t2.name)
ORDER BY column_name
OK, thanks again. I'm not sure how much usable data you would need? I'm not even sure if you need data at all? All that I'm trying to do is determine differences between column headings.
My apologies if I haven't explained myself very well
Please provide the data requested by @ScottPletcher, otherwise it would be guess work. Then you will respond with "Unfortunately, the query didn't work as expected"
Posting data with pictures is one way but very difficult for us to help you as it would take time to recreate it. Here is how you can provide more usable data.
"Usable data" in this case would be the DDL to create the two table structures you want compared.
I'm not sure how you expect someone to write perfect code without sample data to test it on. But I admit I can't always do that. I'm willing to volunteer my time to help others, but not if they don't feel they should even have to provide a basic data/structure setup.
Thanks for sticking with me on this. Here is a sample Table
CREATE TABLE Optimus.dbo.table1 (
header1 VARCHAR(50) NULL
,header2 VARCHAR(50) NULL
,header3 VARCHAR(50) NULL
)
GO
DECLARE @table1 nvarchar(128)
DECLARE @table2 nvarchar(128)
SET @table1 = 'Table1'
SET @table2 = 'Table2'
SELECT *
FROM (
SELECT name AS t1_column_name
FROM sys.columns
WHERE object_id = OBJECT_ID(@table1)
) AS t1
FULL OUTER JOIN (
SELECT name AS t2_column_name
FROM sys.columns
WHERE object_id = OBJECT_ID(@table2)
) AS t2 ON t1.t1_column_name = t2.t2_column_name