子查询错误,不允许我返回超过1的值

时间:2015-02-04 11:16:12

标签: sql sql-server-2008

在我的数据库中,我有一个名为studentEmailAddresses的表,我想要获取每个电子邮件地址并创建一个长字符串,该字符串将包含所有电子邮件地址,以便可以在我的sp_send_dbmail中使用功能

例如,我有两个电子邮件地址Test1@hotmail.comTest2@hotmail.com因此,在子查询结束时,我希望结果集看起来像Test1@hotmail.com; Test2@hotmail.com;。下面显示了我是如何尝试这样做但我收到以下错误消息Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

Declare @emailList varchar (1000)
set @emailList = (Select coalesce(emailAdd + ';', ' ') 
from studentEmailAddresses)
Print @emailList 

5 个答案:

答案 0 :(得分:3)

错误是因为您使用SET进行变量赋值。从查询分配时,SET只能分配标量值。如果查询返回多个值/行,则SET将引发错误(如此处的情况)。 SELECT会将其中一个值分配给变量,并隐藏返回多个值的事实(因此您可能永远不会知道为什么其他地方出现了问题)。您可以将查询编写为:

Declare @emailList varchar (1000)
SET  @emailList  = 
(select emailAdd+ ';' AS 'data()'
FROM @studentEmailAddresses 
FOR XML PATH('')  )

答案 1 :(得分:1)

Declare @emailList varchar (max) = ''
Select @emailList = @emailList + emailAdd + ';' 
from studentEmailAddresses
Print @emailList 

答案 2 :(得分:1)

试试这个:

Declare @emailList varchar (1000) = ''
Select @emailList += coalesce(emailAdd + ';', ' ') 
from studentEmailAddresses
Print @emailList

答案 3 :(得分:0)

Declare @emailList varchar (1000)
SET @emailList=''
Select @emailList =@emailList +  coalesce(emailAdd + ';', ' ') 
from studentEmailAddresses
Print @emailList

答案 4 :(得分:0)

在SQL Server中:

Declare @emailList varchar (1000)
SET @emailList=''
Select @emailList = @emailList +  coalesce(emailAdd + ';', ' ') 
from studentEmailAddresses
Print @emailList

在MySQL中:

DECLARE emailList VARCHAR(1000);
SET emailList='';
SELECT CONCAT(emailList, emailAdd, '; ') INTO  emailList
FROM studentEmailAddresses;
SELECT emailList FROM DUAL;

请注意,DUAL是MySQL中的虚拟表,您只需选择emailList as,

即可
SELECT emailList;

谢谢。