如何将查询结果转换为字符串并将其插入表行

时间:2019-04-05 06:59:28

标签: sql sql-server sql-server-2014

我收到一个错误,那就是子查询返回多个值,现在我知道了,我想将该子查询结果转换为字符串,然后将该字符串插入表中的相同位置

我已经尝试过使用循环,但是由于除了查询之外,我无法在其他任何地方使用循环,因此并没有太大帮助。

这是我正在使用的查询

SELECT DISTINCT LiveCampaign_SubscriberList_Email.Email, Firstname, Lastname, dbo.spValueToString(Subscribed) AS Subscribed,

dbo.spValueToString((SELECT COUNT(*) 
    FROM tblEmailBlackList
    WHERE tblEmailBlackList.Email = LiveCampaign_SubscriberList_Email.Email and tblEmailBlackList.PortalID = -2)) As GeneralBlockList,

(SELECT DISTINCT PortalLocalization.PortalName
    FROM tblEmailBlackList
    LEFT JOIN tblLiveCampaignSettings ON tblLiveCampaignSettings.ModuleID = tblEmailBlackList.ModuleID
    LEFT JOIN PortalLocalization ON PortalLocalization.PortalID = tblEmailBlackList.PortalID AND PortalLocalization.CultureCode = 'sl-SI'
    LEFT JOIN #tmp ON tblEmailBlackList.Email = #tmp.Email COLLATE Slovenian_CI_AS
    WHERE LiveCampaign_SubscriberList_Email.Email = #tmp.Email COLLATE Slovenian_CI_AS
    AND tblEmailBlackList.PortalID >= 0 OR tblEmailBlackList.PortalID =- 1)
    AS LocalBlockList

FROM LiveCampaign_SubscriberList_Email

这是我需要转换为字符串的部分:

(SELECT DISTINCT PortalLocalization.PortalName
    FROM tblEmailBlackList
    LEFT JOIN tblLiveCampaignSettings ON tblLiveCampaignSettings.ModuleID = tblEmailBlackList.ModuleID
    LEFT JOIN PortalLocalization ON PortalLocalization.PortalID = tblEmailBlackList.PortalID AND PortalLocalization.CultureCode = 'sl-SI'
    LEFT JOIN #tmp ON tblEmailBlackList.Email = #tmp.Email COLLATE Slovenian_CI_AS
    WHERE LiveCampaign_SubscriberList_Email.Email = #tmp.Email COLLATE Slovenian_CI_AS
    AND tblEmailBlackList.PortalID >= 0 OR tblEmailBlackList.PortalID =- 1)

结果将是一个字符串,然后将其插入表的同一行中,此子查询的结果应为

1 个答案:

答案 0 :(得分:0)

因此,您需要将返回的行聚合为一个行。由于您使用的是SQL Server 2014,因此STRING_AGG不可用,因此我们将使用XML aggregation trick。试试这个:

SELECT DISTINCT LiveCampaign_SubscriberList_Email.Email, Firstname, Lastname, dbo.spValueToString(Subscribed) AS Subscribed,

dbo.spValueToString((SELECT COUNT(*) 
    FROM tblEmailBlackList
    WHERE tblEmailBlackList.Email = LiveCampaign_SubscriberList_Email.Email and tblEmailBlackList.PortalID = -2)) As GeneralBlockList,
STUFF((
    SELECT DISTINCT ',' + PortalLocalization.PortalName
    FROM tblEmailBlackList
    LEFT JOIN tblLiveCampaignSettings ON tblLiveCampaignSettings.ModuleID = tblEmailBlackList.ModuleID
    LEFT JOIN PortalLocalization ON PortalLocalization.PortalID = tblEmailBlackList.PortalID AND PortalLocalization.CultureCode = 'sl-SI'
    LEFT JOIN #tmp ON tblEmailBlackList.Email = #tmp.Email COLLATE Slovenian_CI_AS
    WHERE LiveCampaign_SubscriberList_Email.Email = #tmp.Email COLLATE Slovenian_CI_AS
    AND tblEmailBlackList.PortalID >= 0 OR tblEmailBlackList.PortalID =- 1
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
    AS LocalBlockList

FROM LiveCampaign_SubscriberList_Email