无法摆脱“程序试图返回NULL状态”的错误

时间:2016-05-11 17:34:13

标签: sql sql-server stored-procedures view null

我正在尝试从存储过程中获取值。

USE FoodDB
GO

IF OBJECT_ID('spCalCount') IS NOT NULL
DROP PROC spCalCount
GO

CREATE PROC spCalCount
    @FoodGroup varchar(25) = '%',
    @Name varchar(25) = '%'
AS

DECLARE @NumCalories decimal(4,1) 

SET @NumCalories = (SELECT SUM(MealCalories)
                    FROM CalsPerMeal
                    WHERE FoodGroup LIKE @FoodGroup 
                    AND Name LIKE @Name)

RETURN @NumCalories

CalsPerMeal是一个结合了几个表的视图。这是我能想到的唯一导致错误的事情。

USE FoodDB

DECLARE @Count decimal(4,1)
EXEC @Count = spCalCount 'Fruit', 'Jason'
PRINT 'Jason has eaten ' + CONVERT(varchar,@Count,1) + ' Fruit Calories'

我不断得到的错误是:

The 'spCalCount' procedure attempted to return a status of NULL, which is
not allowed. A status of 0 will be returned instead.
Jason has eaten 0.0 Fruit Calories

我也尝试使用输出参数进行此变体,但仍然为NULL

USE FoodDB
GO

IF OBJECT_ID('spCalCount') IS NOT NULL
DROP PROC spCalCount
GO

CREATE PROC spCalCount
    @NumCalories decimal(4,1) OUTPUT,
    @FoodGroup varchar(25) = '%',
    @Name varchar(50) = '%'
AS
SELECT @NumCalories = (SELECT SUM(MealCalories)
                FROM CalsPerMeal
                WHERE FoodGroup LIKE @FoodGroup 
                AND Name LIKE @Name)

执行:

USE FoodDB

DECLARE @Count decimal(4,1)
EXEC spCalCount @Count OUTPUT, 'Fruit', 'Jason'
SELECT @Count AS JasonFruitCals

这不会给我错误,但仍会返回NULL

2 个答案:

答案 0 :(得分:3)

您的代码看起来像SQL Server,因为KeyValuePair<List<Room>,List<RoomConflict>>值必须是非NULL INT。它警告你它正在将NULL更改为零。

您的查询:

RETURN

必须导致@NumCalories带来NULL,因此没有行到SUM(),因此SQL Server将您的NULL返回转换为零。

最好只通过SET @NumCalories = (SELECT SUM(MealCalories) FROM CalsPerMeal WHERE FoodGroup LIKE @FoodGroup AND Name LIKE @Name) 返回一个执行状态值,如0 = good,-1 = warning,1 =致命错误等。如果你需要传回一个值,就像你一样在这里,使用OUTPUT参数。你只能RETURN一个int,所以如果你想要小数,你需要使用一个输出参数。输出参数可以是任何类型,因此它对于您的小数值是一个不错的选择。

请参阅:https://stackoverflow.com/a/2881863/65223

答案 1 :(得分:0)

您需要将RETURN包装在ISNULL中

RETURN ISNULL(@NumCalories,0)

SQL Server期望一个整数,NULL不是整数值。