我正在使用MS Visual Studio 2012.我遇到了编写子查询的问题。这是整个查询,如下所示:
SELECT ACCOUNTNUM
, NAME
, ADDRESS
, PHONE
, TELEFAX
, INVOICEACCOUNT
, CUSTGROUP
, PAYMTERMID
, CURRENCY
, DIMENSION
, CELLULARPHONE
, STATISTICSGROUP
, PAYMMODE
, NAMEALIAS
, CONTACTPERSONID
, STREET
, PARTYID
, SEGMENTID
, TAXGROUP
, DATAAREAID
, ISNULL((
SELECT PERCENT1 AS DiscCount
FROM PRICEDISCTABLE
WHERE (DATAAREAID = CUSTTABLE.DATAAREAID)
AND (ACCOUNTRELATION = CUSTTABLE.ACCOUNTNUM)
), 0) / 100 AS DiscCount
, (
SELECT NAME
FROM CONTACTPERSON
WHERE (DATAAREAID = CUSTTABLE.DATAAREAID)
AND (CUSTACCOUNT = CUSTTABLE.ACCOUNTNUM)
AND (CONTACTPERSONID = CUSTTABLE.CONTACTPERSONID)
) AS ContactName
, (
SELECT PHONE
FROM CONTACTPERSON AS CONTACTPERSON_1
WHERE (DATAAREAID = CUSTTABLE.DATAAREAID)
AND (CUSTACCOUNT = CUSTTABLE.ACCOUNTNUM)
AND (CONTACTPERSONID = CUSTTABLE.CONTACTPERSONID)
) AS ContactPhone
, ISNULL((
SELECT STATGROUPNAME
FROM CUSTSTATISTICSGROUP
WHERE (DATAAREAID = CUSTTABLE.DATAAREAID)
AND (CUSTSTATISTICSGROUP = CUSTTABLE.STATISTICSGROUP)
), 0) AS StatisticsName
FROM CUSTTABLE
WHERE CUSTGROUP = @ty
AND DATAAREAID = N'OTN'
AND STATISTICSGROUP LIKE @ss;
然后我收到错误
子查询返回的值超过1。这是不允许的 子查询跟随=,!=,<,< =,>,> =或当子查询用作 表达。
答案 0 :(得分:1)
问题来自哪里?
问题是你的一个子查询返回多个值(HEY,ERROR DESCRIPTION SAYS THAT)。
如何找到哪一个?
尝试在select语句中注释掉每个子查询,直到查询正常。
如何解决?
这可能是使用CROSS APPLY的最佳案例。这是你的疑问:
SELECT ACCOUNTNUM
, NAME
, ADDRESS
, PHONE
, TELEFAX
, INVOICEACCOUNT
, CUSTGROUP
, PAYMTERMID
, CURRENCY
, DIMENSION
, CELLULARPHONE
, STATISTICSGROUP
, PAYMMODE
, NAMEALIAS
, CONTACTPERSONID
, STREET
, PARTYID
, SEGMENTID
, TAXGROUP
, DATAAREAID
, ISNULL(T1.DiscCount, 0) / 100 AS DiscCount
, T2.ContactName
, T3.ContactPhone
, ISNULL(T4, 0) AS StatisticsName
FROM CUSTTABLE
CROSS APPLY (
SELECT PERCENT1 AS DiscCount
FROM PRICEDISCTABLE
WHERE DATAAREAID = CUSTTABLE.DATAAREAID
AND ACCOUNTRELATION = CUSTTABLE.ACCOUNTNUM
) AS T1
CROSS APPLY (
SELECT NAME
FROM CONTACTPERSON
WHERE DATAAREAID = CUSTTABLE.DATAAREAID
AND CUSTACCOUNT = CUSTTABLE.ACCOUNTNUM
AND CONTACTPERSONID = CUSTTABLE.CONTACTPERSONID
) AS T2
CROSS APPLY (
SELECT PHONE
FROM CONTACTPERSON AS CONTACTPERSON_1
WHERE DATAAREAID = CUSTTABLE.DATAAREAID
AND CUSTACCOUNT = CUSTTABLE.ACCOUNTNUM
AND CONTACTPERSONID = CUSTTABLE.CONTACTPERSONID
) AS T3
CROSS APPLY (
SELECT STATGROUPNAME
FROM CUSTSTATISTICSGROUP
WHERE DATAAREAID = CUSTTABLE.DATAAREAID
AND CUSTSTATISTICSGROUP = CUSTTABLE.STATISTICSGROUP
) AS T4
WHERE CUSTGROUP = @ty
AND DATAAREAID = N'OTN'
AND STATISTICSGROUP LIKE @ss;
此外,这些可以重写为简单的INNER JOINS。
答案 1 :(得分:0)
遇到此错误时,请尝试单独运行子查询,如果返回了多条记录,则优化条件以确保只返回一条记录。
当然,如果需要多条记录,则需要更改查询以使用连接而不是子查询。