如何从一个表中选择一个随机 ID 并使用它来填充另一个表中的随机数据?



我正在尝试按照本指南插入随机数据以对我的应用程序进行压力测试。

我在某些列上有一些外键,我也想为这些列插入一些随机数据。

假设表Clinics有 5 条记录,ID 为"3,7,90,98,102";对于Activities上的每个插入,我想从这 5 个 ID 中选择一个。尝试过:

Declare @clinicId int
Declare @counter int
Set @counter = 11
While @counter < 12
Begin 
@clinicId = SELECT TOP 1 * FROM Clinics ORDER BY NEWID()
Insert Into Activities values (@clinicId, 100, 10, 90, 2, 65, 1)
Set @counter = @counter + 1
End

但它说Syntax error in proximity of @clinicId.有什么线索吗?

你需要在分配之前top (1)

SELECT TOP (1) @clinicId = ID 
FROM Clinics 
ORDER BY NEWID()

注意:

  • 只能将单个列值分配给标量变量。

如果要分配所有数据,则使用表变量

您的代码可以通过以下方式修复:

set @clinicId = (SELECT TOP 1 clinic_id from ...)

或者你可以通过基于集合的解决方案来摆脱循环和变量(应该替换所有给定的脚本(:

declare @cnt int = 12
Insert Into dbo.Activities (...)
SELECT
c.clinicID, 100, 10, 90, 2, 65, 1
FROM 
(
SELECT TOP (@cnt) 1 dummy
from master.dbo.spt_values
) v
CROSS APPLY (
SELECT TOP (1) c.clinicID
FROM dbo.Clinics c
ORDER BY NEWID()
) c

最新更新