【问题标题】:Subquery returned more than 1 value. This is not permitted when the subquery follows procedure SQL Server子查询返回超过 1 个值。当子查询遵循 SQL Server 过程时,这是不允许的
【发布时间】:2021-02-21 15:32:42
【问题描述】:

为什么这个程序不起作用?

CREATE PROCEDURE [dbo].[p_top5_v2_type_1km]
    @IdCustomer int,
    @idGroupVehicle int  
AS
    DECLARE @start geography
    SET @start = (SELECT location FROM Customer 
                  WHERE idCustomer = @idCustomer )

    SELECT TOP 5 
        idVehicle, idGroupVehicle, brand, model, maxRange, weight, maxSpeed, nameLocation 
    FROM 
        Vehicle 
    WHERE 
        idGroupVehicle = @idGroupVehicle 
        AND @start.STDistance(locationVehicle) / 1000 <= 1
    ORDER BY 
        @start.STDistance(locationVehicle) / 1000 ASC
GO

此程序应列出最近的前 5 辆车,类型车辆是 idGroupVehicle,但我收到此错误

消息 512,级别 16,状态 1,过程 p_top5_type,第 6 行 [批处理开始第 18 行]
子查询返回超过 1 个值。当子查询跟随 =、!=、、>= 或子查询用作表达式时,这是不允许的。

谁能解释为什么这不起作用?

【问题讨论】:

  • 错误信息的哪一部分你不明白?看起来很清楚。
  • 我必须在这个查询中改变什么?
  • 问题出在你的 子查询 ,正如错误告诉你的那样。显然,idCustomer 列在您的表 Customet 中不是唯一值。
  • OP 还需要添加一个 ORDER BY @MarkSchultheiss ,否则 TOP 1 不妨说“任意行”。
  • ORDER BYTOP、@MarkSchultheiss 肯定在范围内。如果你要引入另一个缺陷,那么修复一个缺陷是没有意义的。

标签: sql sql-server procedure


【解决方案1】:

Subuery =>(从客户那里选择位置 哪里 idCustomer = @idCustomer ) 返回一个以上的值 当您使用 SET 语法时会发生这种情况

我认为您在表 Customer 中有双重 idCustomer

如果您可以在表 Customer 中使用双 idCustomer

 SET @start = (SELECT TOP 1 location FROM Customer 
                  WHERE idCustomer = @idCustomer )

或者

SELECT @start = location FROM Customer 
WHERE idCustomer = @idCustomer

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-08
    • 2014-10-21
    • 2012-06-04
    • 2016-08-02
    相关资源
    最近更新 更多