我挣扎着我的存储过程,它增加了“空”'而不是数字
那么为什么以下程序会添加' NULL'而不是介于0和无穷大之间的值?
这是我的程序
ALTER PROCEDURE [dbo].[Plan_Abschluss]
-- My parameters for the stored procedure
@date AS datetime2(7),
@Einrichtung AS Int,
@Mitarbeiter AS Int
AS
BEGIN
-- declare my parameters
DECLARE @PlanStunden AS decimal(18, 2)= null,
@PlanUrlaub AS Int= null,
@oldDate AS datetime2(7)= null,
@oldUrlaubskonto AS Int= null,
@oldStundenKonto AS decimal(18, 2)= null;
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- set the previous month
SET @oldDate= DATEADD(month, -1, @date);
-- get some values from the previous row and set it to my parameters
SELECT @oldUrlaubskonto = ISNULL(CurrentUrlaubskonto,0) ,
@oldStundenKonto = ISNULL(CurrentStundenKonto,0)
FROM [Plan]
WHERE [Jahr] = YEAR(@oldDate)
AND [Monat] = MONTH(@oldDate)
AND [RefMitarbeiterId] = @Mitarbeiter
AND [RefEinrichtungId] = @Einrichtung;
-- get some values from the row i want to update and set it to my parameters
SELECT @PlanStunden = ISNULL(PlanStunden,0) ,
@PlanUrlaub = ISNULL(PlanUrlaub,0)
FROM [Plan]
WHERE [Jahr] = YEAR(@date)
AND [Monat] = MONTH(@date)
AND [RefMitarbeiterId] = @Mitarbeiter
AND [RefEinrichtungId] = @Einrichtung;
-- update the row and do a calculation with my parameters
UPDATE [Plan]
SET Abgeschlossen = 1,
CurrentUrlaubskonto = @oldUrlaubskonto+ @PlanUrlaub,
CurrentStundenKonto = @oldStundenKonto+ @PlanStunden
WHERE [Jahr] = YEAR(@date)
AND [Monat] = MONTH(@date)
AND [RefMitarbeiterId] = @Mitarbeiter
AND [RefEinrichtungId] = @Einrichtung
END
答案 0 :(得分:2)
如果没有返回行,则不会在select
中设置变量。我的猜测是使用select
的第一个@OldDate
根本不匹配任何行。
特别是,变量@oldUrlaubskonto
和@oldStundenKonto
初始化为NULL
,因此在没有匹配记录时永远不会设置它们。解决这个问题的一个简单方法是使用聚合 - 无论如何你都期待一行,所以没关系:
SELECT @oldUrlaubskonto = ISNULL(max(CurrentUrlaubskonto), 0) ,
@oldStundenKonto = ISNULL(max(CurrentStundenKonto), 0
如果值仍为NULL
,您也可以在之后设置值。