更新引发错误消息子查询返回了多个值

时间:2018-08-11 14:15:19

标签: sql sql-server

我正在尝试运行此查询:

update [test].[test_data] 
set [test].[test_data].[Attribute] = (select [Attribute Name] 
                                      from [AF].[Producer Well Template] 
                                      where [test].[test_data].[Attribute_old] = [Existing Attribute Name])

它抛出此错误:

  

子查询返回了多个值。当子查询遵循=,!=,<,<=,>,> =或将子查询用作表达式时,不允许这样做。

[AF].[Producer Well Template]表的记录少于[test_data]

谢谢, S

3 个答案:

答案 0 :(得分:1)

这意味着您在下面的内部查询返回的多个现有属性名称值。您的内部查询应该只为[test_data]行中需要更新的每个字段返回一个值。这是有道理的,因为您只能将属性更新为一个值,并且如果子查询有多个返回值,则不知道要使用多个值中的哪个。

printf

答案 1 :(得分:0)

Update [test].[test_data] 
   set [Attribute] = pwt.[Attribute Name] 
from [test].[test_data] td 
  inner join [AF].[Producer Well Template] pwt 
    on td.[Attribute_old]=pwt.[Existing Attribute Name];

但是您仍然必须找到SQL使其成为单个项目。

答案 2 :(得分:0)

我会这样写查询(这样更易读):

update td
    set [Attribute] = (select pwt.[Attribute Name] 
                       from [AF].[Producer Well Template] pwt
                       where td.[Attribute_old] = pwt.[Existing Attribute Name]
                      )
    from [test].[test_data] td;

问题非常明显-子查询中有多个匹配项。您可以通过执行以下操作轻松找到罪魁祸首:

select pwt.[Attribute Name] 
from [AF].[Producer Well Template] pwt
group by pwt.[Existing Attribute Name]
having count(*) > 1;

如果您只是想摆脱错误,请在子查询中使用select top (1)