我有以下比較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)
你的答案對SQL注入非常開放。 'EXEC [usp_comparetables] @ table1 ='myTable',@ table2 ='myTable2',@columnList ='''; DROP TABLE myTable;走; ''''''''只是一個簡單的例子。 SQL注入似乎從來沒有,直到你被它咬了一次。 – Seph