This question is related to this thread, not sure if I am supposed to post this new question in that post or create a new post, but was worried it might not get seen as a follow up question within the old post ...
- I need to replace a bunch of IDs with random but unique new ones in an SQL table.
- I am using t-clausen.dk's code snip from this thread to generate the new IDs.
- I am using a temp table to iterate through the old IDs, generating the new ID, and then updating my table with the new ID. (that part of the solution in this thread)
- My problem is that all of the new IDs end up being the same. How can I get @r to clear out so that it can generate a new number?
Or is there a better way to solve this issue generally? Say without looping ...?
SELECT * INTO #ControlTable FROM tempmaster DECLARE @ei varchar(max) DECLARE @r varchar(8) WHILE EXISTS (SELECT * FROM #ControlTable) BEGIN SELECT @ei = (SELECT TOP 1 externalid FROM #ControlTable ORDER BY externalid ASC) -- CREATE UNIQUE RANDOM ID SELECT @r = coalesce(@r, '') + n FROM (SELECT top 8 CHAR(number) n FROM master..spt_values WHERE type = 'P' AND (number between ascii(0) and ascii(9) or number between ascii('A') and ascii('Z') or number between ascii('a') and ascii('z')) ORDER BY newid()) a -- REPLACE OLD ID UPDATE tempmaster SET externalid = @r WHERE externalid = @ei DELETE #ControlTable WHERE externalid = @ei /*TESTING*/ --SELECT @ei AS EI, @r AS [newID] --SELECT * FROM #ControlTable --SELECT * FROM tempmaster WHERE externalid = @ei OR externalid = @r END drop table #ControlTable
HERE IS AN OUTLINE OF AN ATTEMPT AT A SET-BASED APPROACH
DECLARE @r varchar(8);
SELECT oid, startdate, enddate,
coalesce(@r, '') + n
FROM (SELECT TOP 8
CHAR(number) n FROM
master..spt_values
WHERE type = 'P' AND
(number between ascii(0) and ascii(9)
or number between ascii('A') and ascii('Z')
or number between ascii('a') and ascii('z'))
ORDER BY newid())
as externalid
FROM MasterTable