【问题标题】:How to Update a row with some declard and setted Values如何使用一些声明和设置的值更新行
【发布时间】:2014-07-22 12:20:12
【问题描述】:

您好,我的存储过程添加了“NULL”而不是数字

那么为什么下面的过程会添加 '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

【问题讨论】:

  • NULL 设置了哪些值?
  • @GordonLinoff CurrentUrlaubskonto 和 CurrentStundenKonto

标签: sql stored-procedures sql-update declare


【解决方案1】:

如果没有返回行,则不会在 select 中设置变量。我的猜测是第一个使用@OldDateselect 根本不匹配任何行。

特别是变量@oldUrlaubskonto@oldStundenKonto 被初始化为NULL,所以当没有匹配记录时它们永远不会被设置。解决此问题的一种简单方法是使用聚合 - 无论如何您都希望有一行,所以没关系:

SELECT  @oldUrlaubskonto =  ISNULL(max(CurrentUrlaubskonto), 0) ,
        @oldStundenKonto =  ISNULL(max(CurrentStundenKonto), 0

如果还是NULL,也可以在后面设置值。

【讨论】:

    猜你喜欢
    • 2021-09-28
    • 1970-01-01
    • 1970-01-01
    • 2020-02-17
    • 2019-09-16
    • 1970-01-01
    • 2022-12-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多