TSQL foreach查询

时间:2011-04-27 19:34:39

标签: tsql

我正在尝试为我的数据库中的所有人生成随机SSN,但是我这样做有点困难。

这是我正在使用的查询:

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
    );

它可以正常生成随机SSN,但它只执行一次,即每个人都获得相同的SSN。

如何让每个用户生成一个新的随机SSN?

2 个答案:

答案 0 :(得分:1)

答案 1 :(得分:1)

试试这个:

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)