0
Help us understand the problem. What are the problem?

More than 3 years have passed since last update.

posted at

SQLServerでランダム文字取得ストアドを作ってみました

SQLServerでランダム文字取得ストアドを作ってみました

テストデータを作るのに欲しかったので。

コード

RandomString.sql
CREATE PROCEDURE [dbo].[RandomString](@length INT , @ret NVARCHAR(100) OUTPUT)
AS
    DECLARE @count AS INT;
    DECLARE @randitem AS NVARCHAR(62) = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';

    SET @ret = '';
    SET @count = 0;

    WHILE @count < @length
    BEGIN
       SELECT @ret = @ret + SUBSTRING(@randitem, CONVERT(int, (CEILING(RAND() * LEN(@randitem)))), 1);
       SET @count = @count + 1;
    END;

    RETURN;
GO

使い方

DECLARE @RC int
DECLARE @Length int = 30
DECLARE @ret nvarchar(100)

EXECUTE @RC = [dbo].[RandomString] 
   @Length
  ,@ret OUTPUT

SELECT @ret AS RandomString;

GO

結果

Q8EDUF8iyOnvOpB3s87zoUYMhBI5EJ
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Sign upLogin
0
Help us understand the problem. What are the problem?