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

问题描述 投票:0回答:2

我正在尝试插入随机数据,为我的应用程序进行压力测试,遵循此guideline

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

假设表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。有线索吗?

sql-server
2个回答
1
投票

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

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

2
投票

在转让之前你需要top (1)

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

注意 :

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

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

© www.soinside.com 2019 - 2024. All rights reserved.