当我尝试使用多个select语句运行insert语句时,我收到错误
Msg 512,Level 16,State 1,Line 3 Subquery返回的值超过1 值。当子查询遵循=,!=,<,< =,>,> =或子查询用作表达式时,不允许这样做。声明已经终止。
我的查询
insert into zzz_fkp_tbl2 (fname,lname) values
(
(select top 20 percent [FNAME] from ZZZ_FKP_NEW_PATIENT order by newid())
,(select top 20 percent lname from ZZZ_FKP_NEW_PATIENT order by newid())
);
但是当我使用single语句运行insert语句时,此查询成功运行,如:
insert into zzz_fkp_tbl2 (lname)
select top 20 percent lname from ZZZ_FKP_NEW_PATIENT order by newid();
为什么我在使用多个select语句时收到错误Subquery returned more than 1 value
。但是insert语句在单个select语句中运行正常。在这种情况下,如何使用多个select语句?
我的要求是为fname和lname选择单独的随机行,但不能在一起,即应随机选择fname并随机选择lname。
目标表
create table zzz_fkp_tbl2
(
zzz_fkp_tbl2_id int identity(1,1) not null
,name varchar(200)
,fname varchar(200)
,lname varchar(200)
,gender int
,address int
,age varchar(10)
);
答案 0 :(得分:4)
您正在寻找此
INSERT INTO zzz_fkp_tbl2
(fname,
lname)
SELECT TOP 20 PERCENT [FNAME],
lname
FROM ZZZ_FKP_NEW_PATIENT
ORDER BY Newid()
更新:
SELECT TOP 20 PERCENT a.FNAME,
b.lname
FROM ZZZ_FKP_NEW_PATIENT
OUTER apply (SELECT TOP 1 [FNAME] ZZZ_FKP_NEW_PATIENT
ORDER BY Newid()) a ([FNAME])
OUTER apply (SELECT TOP 1 lname ZZZ_FKP_NEW_PATIENT
ORDER BY Newid()) b (lname)
答案 1 :(得分:0)
insert into zzz_fkp_tbl2 (fname,lname) values
(
(select top(1) [FNAME] from ZZZ_FKP_NEW_PATIENT order by newid())
,(select top(1) lname from ZZZ_FKP_NEW_PATIENT order by newid())
);