在SQL中生成随机中间首字母

时间:2014-07-19 06:53:19

标签: sql-server tsql data-generation

我怎样才能在TSQL中编写一个程序来遍历表格的每一行并为中间的初始列生成一个随机字母?

2 个答案:

答案 0 :(得分:2)

您可以使用简单的UPDATE语句,而不是为其编写程序。一个例子是(使用答案中的表/字段名称);

UPDATE Contact SET conMName = CHAR(ABS(CHECKSUM(NEWID()))%26+65)

答案 1 :(得分:0)

假设您的Identity列保持增加1的整数,标识列称为conID,您的表称为EDI.Contact,保留中间名称的列称为conMName,下面的代码将起作用;

DECLARE 
    @Counter INT = '1'
    , @GeneratedLetter CHAR(1)
    , @NumberOfRows INT = (SELECT COUNT(*) FROM EDI.Contact) -- Replace with your table name
    , @LetterNumber INT
WHILE (@Counter < @NumberOfRows +1)
BEGIN
SET @LetterNumber = (CAST(RAND(CHECKSUM(NEWID())) * 26 as INT) + 1)
IF @LetterNumber = '1' 
SET @GeneratedLetter = 'A'
ELSE IF @LetterNumber = '2'
SET @GeneratedLetter = 'B'
ELSE IF @LetterNumber = '3'
SET @GeneratedLetter = 'C'
ELSE IF @LetterNumber = '4'
SET @GeneratedLetter = 'D'
ELSE IF @LetterNumber = '5'
SET @GeneratedLetter = 'E'
ELSE IF @LetterNumber = '6'
SET @GeneratedLetter = 'F'
ELSE IF @LetterNumber = '7'
SET @GeneratedLetter = 'G'
ELSE IF @LetterNumber = '8'
SET @GeneratedLetter = 'H'
ELSE IF @LetterNumber = '9'
SET @GeneratedLetter = 'I'
ELSE IF @LetterNumber = '10'
SET @GeneratedLetter = 'J'
ELSE IF @LetterNumber = '11'
SET @GeneratedLetter = 'K'
ELSE IF @LetterNumber = '12'
SET @GeneratedLetter = 'L'
ELSE IF @LetterNumber = '13'
SET @GeneratedLetter = 'M'
ELSE IF @LetterNumber = '14'
SET @GeneratedLetter = 'N'
ELSE IF @LetterNumber = '15'
SET @GeneratedLetter = 'O'
ELSE IF @LetterNumber = '16'
SET @GeneratedLetter = 'P'
ELSE IF @LetterNumber = '17'
SET @GeneratedLetter = 'Q'
ELSE IF @LetterNumber = '18'
SET @GeneratedLetter = 'R'
ELSE IF @LetterNumber = '19'
SET @GeneratedLetter = 'S'
ELSE IF @LetterNumber = '20'
SET @GeneratedLetter = 'T'
ELSE IF @LetterNumber = '21'
SET @GeneratedLetter = 'U'
ELSE IF @LetterNumber = '22'
SET @GeneratedLetter = 'V'
ELSE IF @LetterNumber = '23'
SET @GeneratedLetter = 'W'
ELSE IF @LetterNumber = '24'
SET @GeneratedLetter = 'X'
ELSE IF @LetterNumber = '25'
SET @GeneratedLetter = 'Y'
ELSE IF @LetterNumber = '26'
SET @GeneratedLetter = 'Z'
UPDATE EDI.Contact -- Replace with your table name
SET conMName = @GeneratedLetter -- Replace with column that holds middle names
WHERE conId = @Counter -- Replace with identity column name
SET @Counter = (@Counter + 1)
END