子查询返回的值超过1。这是不允许的。错误在哪里?

时间:2015-05-04 16:36:08

标签: sql sql-server

我得到错误:

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

我感到困惑,因为它告诉我错误发生在第2行,我不明白这是怎么回事?

UPDATE .patient_insurance
SET insurance_sequence = CASE def_cob
        WHEN 1 THEN 'Primary'
        WHEN 2 THEN 'Secondary'
        WHEN 3 THEN 'Third'
        WHEN 4 THEN 'Fourth'
        WHEN 5 THEN 'Fifth'
        WHEN 6 THEN 'Sixth'
        WHEN 7 THEN 'Seventh'
        WHEN 8 THEN 'Eigth'
        WHEN 9 THEN 'Ninth'
        END
    ,status_flag = CASE active_ind
        WHEN 'Y' THEN 'Yes'
        ELSE 'No'
        END
    ,insurance_company_id = (
        SELECT id
        FROM insurance
        WHERE companyname = payer_name
        )
    ,insurance_number = policy_nbr
    ,policy_group = group_nbr
FROM person_payer
    ,person
WHERE person.person_id = person_payer.person_id
    AND EXISTS (
        SELECT *
        FROM patient_insurance
        WHERE cast(person_payer_id AS VARCHAR(50)) = isnull(custom_field_22, '')
        )
    AND isnull(custom_field_22, '') = cast(person_payer_id AS VARCHAR(50))

2 个答案:

答案 0 :(得分:5)

这一行

insurance_company_id =
(select id from insurance where companyname = payer_name),

它告诉您该子查询带有多行,并且不能将多行的值分配给单行上的单个列。

答案 1 :(得分:1)

这些错误中的行号通常毫无意义。它通常会为您提供启动它的语句的位置,在您的情况下可能在第2行。

将其更改为SELECT,以便查看子查询为基表中的每一行返回的行的COUNT()。他们中的一个或多个有多个insurance.id,由子查询返回。

例如:

select
    person_payer_id,
    payer_name,
    (select count(id) from insurance where companyname = payer_name) as payer_name_count,
    insurance_number = policy_nbr,
    policy_group = group_nbr
from
    person_payer,person
where
    person.person_id = person_payer.person_id
    and exists 
    (
    select
        *
    from
        patient_insurance
    where
        cast(person_payer_id as varchar(50)) = isnull(custom_field_22,'') )
        and isnull(custom_field_22,'') = cast(person_payer_id as varchar(50)
    )

这是一个隔离这些违规子查询的版本,不考虑exists()子句。

select
    t.*
from
    (
    select
        person_payer_id,
        payer_name,
        (select COUNT(id) from insurance where companyname = payer_name) AS payer_name_count,
        insurance_number = policy_nbr,
        policy_group = group_nbr
    from
        person_payer,person
    where
        person.person_id = person_payer.person_id
    ) AS T
where
    T.payer_name_count > 1

更简单的是,对保险的查询会在这种情况下找到问题。

SELECT
  companyname,
  count(*)
FROM
  insurance
GROUP BY
  companyname
HAVING
  count(*) > 1

另外,请对代码格式做一些事情。格式化是免费的,并避免维护噩梦。这段代码很难为下一个人(可能是你)阅读。