Update语句插入新行而不是更新

时间:2015-04-10 16:37:26

标签: c# sql stored-procedures

我的代码应该只更新表中的单个特定行。我使用一个简单的过程来更新当前应用程序中的记录,除了这种情况外,它运行没有任何问题。每次运行查询时,它实际上都会插入一个新行,而不仅仅是更新现有行:

所以这是我的c#代码:

        try
        {
            command.Parameters.Clear();
            command.Parameters.AddRange(vars);
            command.CommandText = "Update" + tableName;

            conn.Open();
            command.ExecuteNonQuery();
            conn.Close();

            this.GetData(tableName);
        }
        catch
        {
            throw;
        }

这是我的SQL代码(请输入'Alter Procedure'语句,我只想获得该程序的核心脚本):

    ALTER procedure [dbo].[UpdateExpenditureItems]
    (@ID int,
    @Name nvarchar(50),
    @IsGroup bit,
    @Parent nvarchar(50),
    @Description nvarchar(50)
    )

    AS

    Begin

--a new inserted row seems to be a result of running IF statement rather than ELSE
    if @Parent != null
        begin
        declare @ParentID int

        set @ParentID = (select ID from ExpenditureItems where Name=@Parent);

        UPDATE ExpenditureItems SET Name =@Name, Parent =@ParentID, [Description] =@Description, IsGroup = @IsGroup WHERE ID=@ID;

        end
    else
        begin
        UPDATE ExpenditureItems SET Name =@Name, [Description] =@Description WHERE ID=@ID
        end
    end

由于声誉限制,我无法发布截图... 提前谢谢。

2 个答案:

答案 0 :(得分:1)

 @Parent != null

这不是你在SQL中检查null的方法

将其更改为:

 @Parent is not null

答案 1 :(得分:0)

原因是当前表单是从另一个继承的,当我按下OK按钮时,基类的OK按钮单击事件首先被触发,然后是孩子。

解决方案:要么以运行基类按钮单击事件结束,要么使用virtual和override来覆盖基类方法。

相关问题