0
如何在TSQL中編寫程序來遍歷表的每一行併爲中間初始列生成一個隨機字母?在TSQL中生成隨機中間初始值
如何在TSQL中編寫程序來遍歷表的每一行併爲中間初始列生成一個隨機字母?在TSQL中生成隨機中間初始值
您可以使用簡單的UPDATE語句,而不是爲它編寫程序。一個例子是(使用你的答案中的表/字段名稱);
UPDATE Contact SET conMName = CHAR(ABS(CHECKSUM(NEWID()))%26+65)
假設您的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
該死。我在那裏思考問題。 – CryptoJones
我其實從來沒有聽說過ABS功能。這很酷。 – CryptoJones