小编典典

如何在SQL Server中生成随机数据

sql

我想创建一个存储过程,以便在“视频”表中插入随机数据。我已经为UserProfile表生成了30,000条记录数据。

注意:用户名是视频表中的FK元素。

CREATE TABLE UserProfile 
(
  Username VARCHAR(45)  NOT NULL  ,
  UserPassword VARCHAR(45)  NOT NULL  ,
  Email VARCHAR(45)  NOT NULL  ,
  FName VARCHAR(45)  NOT NULL  ,
  LName VARCHAR(45)  NOT NULL  ,
  Birthdate DATE   ,
  Genger VARCHAR(10)  NOT NULL  ,
  ZipCode INT    ,
  Image VARCHAR(50)      ,

  PRIMARY KEY(Username)
);
GO

CREATE TABLE Video 
(
  VideoId INT  NOT NULL DEFAULT 1000 ,
  Username VARCHAR(45)  NOT NULL  ,
  VideoName VARCHAR(160)  NOT NULL  ,
  UploadTime DATE    ,
  TotalViews INT    ,
  Thumbnail VARCHAR(100)      ,

  PRIMARY KEY(VideoId),
  FOREIGN KEY(Username)
    REFERENCES UserProfile(Username)
);
GO

阅读 336

收藏
2021-04-15

共1个答案

小编典典

即使在SQL中,生成随机数据也不太困难。

例如,要从您的userprofile表中获取一个随机的用户名。

BEGIN
-- get a random row from a table
DECLARE @username VARCHAR(50)
SELECT @username = [Username] FROM (
    SELECT ROW_NUMBER() OVER(ORDER BY [Username]) [row], [Username]
    FROM [UserProfile]
) t 
WHERE t.row = 1 + (SELECT CAST(RAND() * COUNT(*) as INT) FROM [UserProfile])

print(@username)
END

要生成一个随机整数…

BEGIN
-- get a random integer between 3 and 7 (3 + 5 - 1)
DECLARE @totalviews INT
SELECT @totalviews = CAST(RAND() * 5 + 3 as INT)
print(@totalviews)
END

生成随机的varchar字符串

BEGIN
-- get a random varchar ascii char 32 to 128
DECLARE @videoname VARCHAR(160)
DECLARE @length INT
SELECT @videoname = ''
SET @length = CAST(RAND() * 160 as INT)
WHILE @length <> 0
    BEGIN
    SELECT @videoname = @videoname + CHAR(CAST(RAND() * 96 + 32 as INT))
    SET @length = @length - 1
    END
print(@videoname)
END

最后,一个随机的日期

BEGIN
-- get a random datetime +/- 365 days
DECLARE @uploadtime DATETIME
SET @uploadtime = GETDATE() + (365 * 2 * RAND() - 365)
print(@uploadtime)
END
2021-04-15