我正在尝试插入随机数据,为我的应用程序进行压力测试,遵循此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
。有线索吗?
您的代码可以通过以下方式修复:
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
在转让之前你需要top (1)
:
SELECT TOP (1) @clinicId = ID
FROM Clinics
ORDER BY NEWID()
注意 :
如果要分配所有数据,则使用表变量