您将需要一个光标。
如下所示:
CREATE TABLE TempTable ( RowID INT IDENTITY PRIMARY KEY, SomeValue varchar(10))
INSERT INTO TempTable (SomeValue) VALUES( 'A')
INSERT INTO TempTable (SomeValue) VALUES( 'B')
INSERT INTO TempTable (SomeValue) VALUES( 'B')
INSERT INTO TempTable (SomeValue) VALUES( 'B')
INSERT INTO TempTable (SomeValue) VALUES( 'C')
INSERT INTO TempTable (SomeValue) VALUES( 'C')
INSERT INTO TempTable (SomeValue) VALUES( 'D')
INSERT INTO TempTable (SomeValue) VALUES( 'D')
INSERT INTO TempTable (SomeValue) VALUES( 'D')
INSERT INTO TempTable (SomeValue) VALUES( 'D')
CREATE TABLE #Counts (SomeValue varchar(10), ValCount int CONSTRAINT COunts_Unique UNIQUE(SomeValue))
INSERT INTO #Counts(SomeValue, ValCount)
SELECT DISTINCT SomeValue, 0 FROM TempTable
DECLARE @RowID int
DECLARE @SomeValue VARCHAR(10)
DECLARE @ValCount int
DECLARE curs CURSOR for SELECT RowID, SomeValue FROM TempTable ORDER BY RowID ASC
OPEN curs
FETCH NEXT FROM curs into @RowID, @SomeValue
WHILE(@@FETCH_STATUS = 0)
BEGIN
SELECT @ValCount = ValCount FROM #Counts WHERE SomeValue = @SomeValue
IF(@ValCount > 0)
BEGIN
UPDATE TempTable
SET SomeValue = SomeValue + '(' + Convert(varchar, @valCount) + ')'
WHERE RowID = @RowID
END
UPDATE #Counts SET ValCount = ValCount + 1 where SomeValue = @SomeValue
FETCH NEXT FROM curs into @RowID, @SomeValue
END
CLOSE curs
DEALLOCATE curs
DROP TABLE #Counts