0

我有以下代码

  DECLARE @ProjectID INT
    DECLARE @getSLAPrjectID CURSOR
    SET @getSLAPrjectID = CURSOR FOR SELECT ProjectID FROM SLA

    OPEN @getSLAPrjectID

    FETCH NEXT
    FROM @getSLAPrjectID INTO @ProjectID
    WHILE @@FETCH_STATUS = 0
    BEGIN

    BEGIN

    SET @ScheduleVariance = (select case when (DATEDIFF(day,PlannedStartDate,PlannedEndDate)=0) THEN 0 ELSE (DATEDIFF(day,ActualStartDate,ActualEndDate)-DATEDIFF(day,PlannedStartDate,PlannedEndDate))/CAST(DATEDIFF(day,PlannedStartDate,PlannedEndDate) as float) END from SLA)

    -- other piece of code that is working fine

    END

    FETCH NEXT
    FROM @getSLAPrjectID INTO @ProjectID

    END

    CLOSE @getSLAPrjectID
    DEALLOCATE @getSLAPrjectID

    --end

我收到以下错误:子查询返回超过 1 个值。当子查询跟随 =、!=、<、<=、>、>= 或子查询用作表达式时,这是不允许的。

请让我知道在这段代码中是否有任何替代 CASE 语句或替代标量变量的方法。

4

4 回答 4

1

请尝试在子查询中使用 where 条件 SLA.ProjectID = @ProjectID。

SET @ScheduleVariance = (select case when (DATEDIFF(day,PlannedStartDate,PlannedEndDate)=0) THEN 0 ELSE (DATEDIFF(day,ActualStartDate,ActualEndDate)-DATEDIFF(day,PlannedStartDate,PlannedEndDate))/CAST(DATEDIFF(day,PlannedStartDate,PlannedEndDate) as float) END from SLA where SLA.ProjectID = @ProjectID)
于 2012-08-08T13:08:54.687 回答
0

显然,这一行返回不止一行:

SET @ScheduleVariance = (select case when (DATEDIFF(day,PlannedStartDate,PlannedEndDate)=0)
                                     THEN 0
                                     ELSE (DATEDIFF(day,ActualStartDate,ActualEndDate)-DATEDIFF(day,PlannedStartDate,PlannedEndDate))/CAST(DATEDIFF(day,PlannedStartDate,PlannedEndDate) as float)
                         END from SLA)

您需要以下条件之一来获取一行:WHERE 子句、聚合函数 (WHERE ?) 或 TOP 1。

于 2012-08-08T13:10:40.060 回答
0

很可能是因为表 SLA 包含不止一行。要解决它,您应该添加一个 WHERE 子句,将结果缩小到一行。

我强烈建议不要使用 TOP 1,除非您绝对确定行集的第一行(正确排序)就是您要查找的行。

于 2012-08-08T13:08:44.067 回答
0

SLA 中有超过 1 行。TOP 1只要您使用ORDER BY确保查询是确定性的,您就可以解决这个问题。

SELECT  TOP 1 @ScheduleVariance = CASE WHEN (DATEDIFF(DAY, PlannedStartDate,PlannedEndDate) = 0) THEN 0 
                                ELSE (DATEDIFF(DAY, ActualStartDate, ActualEndDate) / CAST(DATEDIFF(DAY,PlannedStartDate, PlannedEndDate) AS FLOAT)) - 1 
                            END 
FROM    SLA
ORDER BY ProjectID

但是,我怀疑您的查询中也缺少 where 子句。

SELECT  @ScheduleVariance = CASE WHEN (DATEDIFF(DAY, PlannedStartDate,PlannedEndDate) = 0) THEN 0 
                                ELSE (DATEDIFF(DAY, ActualStartDate, ActualEndDate) / CAST(DATEDIFF(DAY,PlannedStartDate, PlannedEndDate) AS FLOAT)) - 1 
                            END 
FROM    SLA
WHERE   ProjectID = @ProjectID

或者

SET @ScheduleVariance = 
    (   SELECT  CASE WHEN (DATEDIFF(day,PlannedStartDate,PlannedEndDate) = 0) THEN 0 
                    ELSE (DATEDIFF(day, ActualStartDate, ActualEndDate) / CAST(DATEDIFF(DAY,PlannedStartDate, PlannedEndDate) AS FLOAT)) - 1 
                END 
        FROM    SLA
        WHERE   ProjectID = @ProjectID
    )

注意,我也整理了你的计算,所以改变了

(x - y) / y 

(x / y) - 1
于 2012-08-08T13:18:27.067 回答