mardi 17 octobre 2017

How to generate random nvarchars in sql server

I have created a stored procedure by the help of some links on this site as below:
How to insert Huge dummy data to Sql server
What is the most efficient way to generate 8 character random alphanumeric string in TSQL?

My stored procedure:

IF  EXISTS (SELECT 1 FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[DUMMY_INSERT]') AND type in (N'P', N'PC'))
BEGIN
    DROP PROCEDURE  DUMMY_INSERT
END
GO
CREATE PROCEDURE DUMMY_INSERT (
@noOfRecords INT
)
AS
BEGIN

DECLARE @r varchar(8)

SELECT @r = coalesce(@r, '') +CHAR(
CASE WHEN r between 0 and 9 THEN 48
WHEN r between 10 and 35 THEN 55
ELSE 61 END + r)
FROM
master..spt_values
CROSS JOIN
(SELECT CAST(RAND(ABS(CHECKSUM(NEWID()))) *61 as int) r) a
WHERE type = 'P' AND number < 8

DECLARE @count int
SET @count = 1;

WHILE (@count < @noOfRecords)
BEGIN
    INSERT INTO Tbl_Customer(name)
     VALUES(@r);

     SET @count = @count + 1;
END
END

When execution, it will insert @noOfRecords (given by user) records with Same names generated as @r. How can I make @r different random nvarchar for each generated record.




Aucun commentaire:

Enregistrer un commentaire