I have the below compare sql code.
Both tables contain a column IDCodeField.
How can I compare only IDCodeField, but return all fields if match IDCodeField?
Currently I am using below, however, it will compare all fields instead of IDCodeField only.
ALTER PROCEDURE [dbo].[usp_comparetables](@table1 varchar(100),
@table2 Varchar(100), @columnlist Varchar(1000))
AS
DECLARE @sql VARCHAR(8000)
SET @sql =
'SELECT ''' + @table1 + ''' AS DataState, * FROM
(SELECT ' + @columnlist + ' FROM ' + @table1 + '
EXCEPT
SELECT ' + @columnlist + ' FROM ' + @table2 + ') x
UNION
SELECT ''' + @table2 + ''' AS DataState, * from
(SELECT ' + @columnlist + ' FROM ' + @table2 + '
INTERSECT
SELECT ' + @columnlist + ' FROM ' + @table1 +') x'
EXEC(@sql)
Used Answer:
DECLARE @sql VARCHAR(8000)
SET @sql =
'SELECT ''' + @table1 + ''' AS DataState, '+@columnlist+' FROM ' + @table1 + ' where '+@compareparameter+' not in (select '+@compareparameter+' from '+@table2+')
UNION ALL
SELECT ''' + @table2 + ''' AS DataState, '+@columnlist+' FROM ' + @table2 + ' where '+@compareparameter+' not in (select '+@compareparameter+' from '+@table1+')'
EXEC(@sql)
I think you want all rows from
Table1andTable2, such that eachIDCodeFieldvalues only appears in one of the tables or the other. You wish to exclude rows where the same value appears in both tables.Ignoring, for the moment, the question of what to do if the same value appears in the same table, the simplest query would be:
This will give you the results, but possibly not in the format you’re seeking – the result rows will be as wide as both tables combined, and the columns from the non-matching table will be
NULL.Or, we could do it in the
UNIONstyle from your question.Both of the above queries will return rows if the same
IDCodeFieldvalue is duplicated only within a single table. If you wish to exclude this possibility, you might try finding the unique values first:(Of course, all the uses of
SELECT *above should be replaced with appropriate column lists)