1

Combining some examples, I came up with the following query (fields and table names have been anonymised soI hope I didn't insert typos).

UPDATE destinationTable
SET destinationField = t2.value
FROM destinationTable t1
CROSS APPLY (
    SELECT TOP 1 'SomeRequiredPrefix ' + sourceField as value
    FROM #sourceTable
    WHERE sourceField <> ''
    ORDER BY NEWID()
    ) t2

Problem Currently, all records get the same value into destinationField , value needs to be random and different. I'm probably missing something here.

1 Answer 1

2

Here's a possible solution. Using CTE's assign row numbers to both tables based on random order. Join the tables together using that rownumber and update the rows accordingly.

;WITH 
dt AS 
(SELECT *, ROW_NUMBER() OVER (ORDER BY NEWID()) AS RowNum
FROM dbo.destinationtable),
st AS
(SELECT *, ROW_NUMBER() OVER (ORDER BY NEWID()) AS RowNum
FROM dbo.#sourcetable)

UPDATE dt
SET dt.destinationfield = 'SomeRequiredPrefix ' + st.sourcefield
FROM dt
JOIN st ON dt.RowNum = st.RowNum

UPDATED SOLUTION

I used CROSS JOIN to get all possibilities since you have less rows in source table. Then assign random rownumbers and only take 1 row for each destination field.

;WITH cte
AS
(
    SELECT *, ROW_NUMBER() OVER (PARTITION BY destinationfield ORDER BY NEWID()) AS Rownum
    FROM destinationtable
    CROSS JOIN #sourcetable
    WHERE sourcefield <> ''

)

UPDATE cte
SET cte.destinationfield = 'SomeRequiredPrefix ' + sourcefield
WHERE cte.Rownum = 1

SELECT * FROM dbo.destinationtable
Sign up to request clarification or add additional context in comments.

5 Comments

This is working better but not yet doing everything it should. Data are randomise but #sourcetable as far less records the destination table, hence I'm thinking of using a LEFT OUTER JOIN, otherwise #sourceTable is limiting the number of row update in destinations table. Still it seems important to keep "WHERE sourceField <> ''" since a lot of source records have '' in sourceField.
Yet are you sure it's "UPDATE dt"? "Not UPDATE destinationtable"?
In ST: 3.000 in total, but really a lot where sourceField = [blank string]. In DT ~82.000. For now I went for a cursor instead of a single query.
@TTT I've added another possible soluition.
With that one I get (547 row(s) affected), where I should have (82067 row(s) affected). Also the execution time of a cursor is 00:19, the execution time of the updated solution is 00:55, so for now I'm staying with the cursor.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.