我编写了一个带有表名作为参数的存储过程,用于检查此表中是否存在重复的行。语句当然是动态构建的:
INSERT INTO tmpTable
SELECT col1, col2,... FROM table GROUP BY col1, col2, ... HAVING COUNT(*) > 1;
DELETE FROM tablename FROM tablenname
INNER JOIN tmpTable ON ISNULL(tablename.col1, 0) = ISNULL(tmpTable.col1, 0)
AND ISNULL(tablename.col2, 0) = ISNULL(tmpTable.col2, 0)
AND ...;
INSERT INTO tablename SELECT * FROM tmpTable;
到目前为止应该工作,但问题是,当表有blob列时,它会失败,就像文本一样。那些无法在JOIN
中进行比较。我也试过
DELETE FROM tablename GROUP BY col1, col2, ... HAVING COUNT(*) > 1;
但GROUP BY
语句中不支持DELETE
而没有自加入。
此外,无法在 information_schema 中查询此表的主键,因为这些表都没有。
有什么想法吗?感谢。
答案 0 :(得分:1)
由于该语句已经动态构建,因此为了加入,将相关列添加到varchar(max)
。要确定哪些列是不难的:
select c.name, quotename(c.name, '[')
from
sys.columns c
inner join sys.types t on c.system_type_id = t.system_type_id
where
c.object_id = object_id(@TABLE_NAME)
and c.is_computed = 0
and t.name in ('text', 'image', 'timestamp', 'xml')