子查询遵循=,!=,<,< =,>,> =或用作表达式时不允许

时间:2016-08-30 16:38:56

标签: sql sql-server

SELECT 
    a.APOIT AS 'Item', 
    (SELECT SUBSTRING(LTRIM(RTRIM(Requisition)), 1, 6) as Requisition 
     FROM DBO_POLB015.db_datareader.CMSFIL_POLB15 as b 
     WHERE b.PONO = a.APONO and b.Item = a.APOIT) as 'Req', 
    REPLACE(REPLACE(REPLACE(REPLACE(ltrim(rtrim(a.AD30A)) + 
        CASE 
           WHEN STUFF((SELECT '; ' + (LTRIM(RTRIM(AI50A)) + LTRIM(RTRIM(AI50B)) + LTRIM(RTRIM(AI50C)) ) 
                       FROM [DBO_CMSFIL].[dbo].[POTMDI] 
                       LEFT OUTER JOIN [DBO_CMSFIL].[dbo].POTMDT ON POTMDI.APOIT = POTMDT.APOIT AND POTMDI.ADVNO = POTMDT.ADVNO AND POTMDI.ACONO = POTMDT.ACONO AND POTMDI.APONO = POTMDT.APONO 
                       WHERE POTMDI.APONO = a.APONO and POTMDT.APOIT= a.APOIT 
                       FOR XML PATH('')), 1, 1, '') IS NULL
              THEN ''  
              ELSE STUFF((SELECT '; ' + (ltrim(rtrim(AI50A)) + ltrim(rtrim(AI50B)) + ltrim(rtrim(AI50C))) 
                          FROM [DBO_CMSFIL].[dbo].[POTMDI] 
                          LEFT OUTER JOIN [DBO_CMSFIL].[dbo].POTMDT ON POTMDI.APOIT = POTMDT.APOIT AND POTMDI.ADVNO = POTMDT.ADVNO AND POTMDI.ACONO = POTMDT.ACONO AND POTMDI.APONO = POTMDT.APONO 
                          WHERE POTMDI.APONO = a.APONO and POTMDT.APOIT= a.APOIT 
                          FOR XML PATH('')), 1, 1, '') 
             end,
    '&',' & '),'  ',''),''', '\'),'"', '\"') as Description,  
    a.AQTOR AS 'QtyOrdered', 
    A.AUM AS 'Units' 
FROM
    [DBO_CMSFIL].[dbo].[POTMDT] AS a 
WHERE   
    a.APONO = '152988'
ORDER BY 
    a.APOIT

我收到以下消息:

  

子查询返回的值超过1。当子查询遵循=,!=,<,< =,>,> =或子查询用作表达式时,不允许这样做。

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

正如错误消息所示:您有一个子查询,它将多列和/或多行返回到仅允许SINGLE值+行的上下文中。

如果它是多行,您可以通过切换到IN匹配来轻松修复。如果它是多个字段,则表示错误。

SELECT (SELECT * FROM tablewithlotsoforws)  // wrong
SELECT (SELECT singlefield FROM tablewithlotsofrows WHERE match=singlerow) // ok
SELECT ... WHERE foo = (SELECT lotsofrows FROM sometable) // wrong
SELECT ... WHERE foo IN (SELECT lotsofrows FROM sometable) // ok
SELECT ... WHERE foo IN (SELECT lotsofrows, evenmorerows FROM stable) // wrong again