TSQL foreach query [duplicate]
Asked Answered
A

1

0

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?

Achelous answered 27/4, 2011 at 19:34 Comment(0)
I
1

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)
Iaea answered 27/4, 2011 at 19:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.