如果我有一个表格,其中列中的单元格不应具有相同的值,我该如何检查并更新?(我知道我可以在设置中设置约束,但我不想这样做.)
假设列名称称为唯一哈希名称并包含
Peter Peter Peter Dave Dave
等等.我想要转换为:
Peter Peter1 Peter2 Dave Dave1
SQL Server的T-SQL是做什么的?
更新:为了清楚起见,让我们调用表"Persons"和我想要唯一的单元"UniqueName".你能把它作为SELECT语句,所以我可以在更新之前测试结果.我正在使用SQL Server 2005及更高版本.
编辑:我已更改查询以使用您的字段名称并添加"仅选择"查询供您预览.
这实际上很容易...只需使用带有PARTITION子句的ROW_NUMBER():
UPDATE Persons SET UniqueName = temp.DeDupded FROM (SELECT ID, CASE WHEN ROW_NUMBER() OVER (PARTITION BY UniqueName ORDER BY UniqueName) = 1 THEN UniqueName ELSE UniqueName + CONVERT(VARCHAR, ROW_NUMBER() OVER (PARTITION BY UniqueName ORDER BY UniqueName)-1) END AS DeDupded FROM Persons) temp WHERE Persons.ID = temp.ID
如果您想要"仅限选择",那么请转到:
SELECT ID, CASE WHEN ROW_NUMBER() OVER (PARTITION BY UniqueName ORDER BY UniqueName) = 1 THEN UniqueName ELSE UniqueName + CONVERT(VARCHAR, ROW_NUMBER() OVER (PARTITION BY UniqueName ORDER BY UniqueName)-1) END AS DeDupded FROM Persons
再次编辑:如果您正在寻找SQL Server 2000解决方案......
CREATE TABLE #Persons ( ID INT IDENTITY(1, 1), UniqueName VARCHAR(100) ) INSERT INTO #Persons VALUES ('Bob') INSERT INTO #Persons VALUES ('Bob') INSERT INTO #Persons VALUES ('Bob') INSERT INTO #Persons VALUES ('John') INSERT INTO #Persons VALUES ('John') SELECT ID, CASE WHEN Position = 0 THEN UniqueName ELSE UniqueName + (CONVERT(VARCHAR, Position)) END AS UniqueName FROM (SELECT ID, UniqueName, (SELECT COUNT(*) FROM #Persons p2 WHERE p1.UniqueName = p2.UniqueName AND p1.ID > p2.ID) AS Position FROM #Persons p1) _temp DROP TABLE #Persons