2012-05-07 113 views
1

我有以下比較SQL代碼。 這兩個表都包含一個IDCodeField列。 如何僅比較IDCodeField,但如果匹配IDCodeField則返回所有字段?SQL與一列比較,但返回所有列如果匹配

目前我正在使用下面,但是,它將僅比較所有字段而不是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, '[email protected]+' FROM ' + @table1 + ' where '[email protected]+' not in (select '[email protected]+' from '[email protected]+') 
UNION ALL 
SELECT ''' + @table2 + ''' AS DataState, '[email protected]+' FROM ' + @table2 + ' where '[email protected]+' not in (select '[email protected]+' from '[email protected]+')' 
EXEC(@sql) 
+1

你的答案對SQL注入非常開放。 'EXEC [usp_comparetables] @ table1 ='myTable',@ table2 ='myTable2',@columnList ='''; DROP TABLE myTable;走; ''''''''只是一個簡單的例子。 SQL注入似乎從來沒有,直到你被它咬了一次。 – Seph

回答

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 *所有使用應符合相應的列清單替換)

+0

謝謝......我用你的第二種方法......很好用...... – kyusan93

0
select * from table1 t1 
inner join table2 t2 on t1.IDCodeField = t2.IDCodeField 
相關問題