TSQL foreach query [duplicate]
I am trying to generate a random SSN for all the people in my database, however I'm having a little difficulty doing so.
This is the query I'm using:
UPDATE tblTenant SET SSNO开发者_开发百科 = (
SELECT
CAST(A.A as CHAR(1)) + CAST(A.B as CHAR(1)) + CAST(A.C as CHAR(1)) + '-' +
CAST(A.D as CHAR(1)) + CAST(A.E as CHAR(1)) + '-' +
CAST(A.F as CHAR(1)) + CAST(A.G as CHAR(1)) + CAST(A.H as CHAR(1))+ CAST(A.I as CHAR(1))
FROM
(SELECT CAST(RAND() * 10 AS TINYINT) as A, CAST(RAND() * 10 AS TINYINT) as B, CAST(RAND() * 10 AS TINYINT) as C, CAST(RAND() * 10 AS TINYINT) as D, CAST(RAND() * 10 AS TINYINT) as E, CAST(RAND() * 10 AS TINYINT) as F, CAST(RAND() * 10 AS TINYINT) as G, CAST(RAND() * 10 AS TINYINT) as H, CAST(RAND() * 10 AS TINYINT) as I) as A
);
It works correctly for generating a random SSN, however it only executes once, i.e. everyone gets the same SSN.
How can I make it so that every user generates a new random SSN?
Try this:
UPDATE tblTenant
SET SSNO = RIGHT('000'+CAST(ABS((CAST(NEWID() AS VARBINARY))%(1000)) AS VARCHAR(3)),3)+'-'+
RIGHT('00'+CAST(ABS((CAST(NEWID() AS VARBINARY))%(100)) AS VARCHAR(2)),2)+'-'+
RIGHT('0000'+CAST(ABS((CAST(NEWID() AS VARBINARY))%(10000)) AS VARCHAR(4)),4)
精彩评论