SQL与一列比较,但如果匹配则返回所有列

时间:2012-05-07 05:19:46

标签: sql sql-server sql-server-2008

我有以下比较sql代码。 两个表都包含一列IDCodeField。 如何仅比较IDCodeField,但如果匹配IDCodeField,则返回所有字段?

目前我在下面使用,但它只会比较所有字段而不是IDCodeField。

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)

二手答案:

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)

2 个答案:

答案 0 :(得分:3)

认为您希望Table1Table2中的所有行,以便每个IDCodeField值仅出现在其中一个表中或另一个表中。您希望排除两个表中出现相同值的行。

暂时忽略如果相同的值出现在相同的表中该怎么办的问题,最简单的查询将是:

SELECT * from Table1 T1 full outer join Table2
ON T1.IDCodeField = T2.IDCodeField
WHERE T1.IDCodeField is null or T2.IDCodeField is null

这将为您提供结果,但可能不是您正在寻找的格式 - 结果行将与两个表组合的一样宽,并且非匹配表中的列将为NULL

或者,我们可以根据您的问题以UNION样式执行此操作。

SELECT * from Table1 where IDCodeField not in (select IDCodeField from Table2)
UNION ALL
SELECT * from Table2 where IDCodeField not in (select IDCOdeField from Table1)

如果仅在单个表中重复相同的IDCodeField值,则上述两个查询返回行。如果您希望排除这种可能性,可以先尝试查找唯一值:

;With UniqueIDs as (
    SELECT IDCodeField
    FROM (
        SELECT IDCodeField from Table1
        union all
        select IDCodeField from Table2) t
    GROUP BY IDCodeField
    HAVING COUNT(*) = 1
)
SELECT * from (
    SELECT * from Table1
    union all
    select * from Table2
) t
  INNER JOIN
UniqueIDs u
  ON
    t.IDCodeField = u.IDCodeField

(当然,上面SELECT *的所有用法都应该用适当的列表替换)

答案 1 :(得分:0)

select * from table1 t1
inner join table2 t2 on t1.IDCodeField = t2.IDCodeField