SQLServer中出错:子查询返回的值超过1

时间:2016-11-20 13:17:19

标签: sql-server

我想从两个不同的表(姓氏和名称)插入Clients表数据。此外,我想有一个第三栏(电子邮件),这是前两个专栏。当我尝试下面的代码时,它会给我以下错误:"子查询返回的值超过1"。

insert into CLIENTS (LastName,Firstname, EMAIL)
select (select top 150 Surname from Surname order by  NEWID()),
   (select top 150 Name from Name order by Newid()),
   (select concat(concat(FisrtName, LastName),'@novaims.com') from clients);

你能帮我理解问题出在哪里吗?

2 个答案:

答案 0 :(得分:1)

错误消息很明显,您的子查询可能会导致多条记录。试试这个

;WITH cte
     AS (SELECT 1 AS val
         UNION ALL
         SELECT val + 1
         FROM   cte
         WHERE  val < 150)
SELECT FisrtName,
       LastName,
       Concat(FisrtName, LastName, '@novaims.com')
FROM   cte
       OUTER apply (SELECT TOP 1 Surname FROM Surname ORDER  BY Newid()) s (FisrtName)
       OUTER apply (SELECT TOP 1 NAME FROM NAME ORDER  BY Newid()) n (LastName) 
   Option (Maxrecursion 0)

答案 1 :(得分:0)

您需要将表引用移动到from子句。我认为这样做你想要的:

insert into CLIENTS (LastName, Firstname, EMAIL)
    select surname, name, concat(name, surname, '@novaims.com')
    from (select Surname, row_number() over (order by newid()) as seqnum
          from Surname
         ) s join
         (select Name, row_number() over (order by newid()) as seqnum
          from Name
         )
         on n.seqnum = s.seqnum;

另一种方法使用apply

insert into CLIENTS (LastName, Firstname, EMAIL)
    select top 150 s.surname, n.name, concat(n.name, s.surname, '@novaims.com')
    from surname s cross apply
         (select top 1 n.*
          from names n
          order by newid()
         ) n
    order by newid();

这与您最初的想法更相似。但请注意,同一名称可以出现多次。对于第一个版本,性能应该更好(因为排序只在每个表上发生一次)。