2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

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

Posted at

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
2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?