简体   繁体   中英

Record in table is not updated when another record is null

I already posted the similar question by with different interpretation.

I'm looking for the solution to the following problem:

I have a stored procedure that is called from my code.

I need to update a record in my table and set it to either 1 or 0. It is a bit datatype.

My stored procedure accepts 3 parameters: region, isActive and Number:

This is my stored procedure:

ALTER PROCEDURE [dbo].[SPU_UpdateEmai] 

@region char(2),
@isoNum varchar(10),
@isActive bit

AS
BEGIN
    SET NOCOUNT ON;

    UPDATE MyTable
    SET isActive = @isActive, updatedate = GETDATE()    
    WHERE region = @region AND isonumber = @isoNum

END

When @isoNumber is not empty, then I can update my isActive field, if @isoNumber is empty, nothing happens.

When simply executing update:

    UPDATE ActivateEmailSendToIso
    SET isActive = 0, updatedate = GETDATE()    
    WHERE region = '04' AND isonumber is null

everything is fine. But when running the code, update does not happen. This is the code:

    using (SqlCommand cmd = new SqlCommand("SP_UpdateEmail", conn))
    {
        conn.Open();
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("@region", actData.Region);
        //cmd.Parameters.AddWithValue("@isoNum", actData.IsoNumber);
        cmd.Parameters.AddWithValue("@isoNum", (actData.Equals(String.Empty)) ? (object)DBNull.Value : actData.IsoNumber);
        cmd.Parameters.AddWithValue("@isActive", actData.IsActive);
        cmd.ExecuteNonQuery();
        isRecordSaved = true;
    }

Everything seems to be fine.

What can possibly be wrong?

Thank you

If you still want to update records when @isoNum is null, then change your procedure to this:

ALTER PROCEDURE [dbo].[SPU_UpdateEmai] 

@region char(2),
@isoNum varchar(10),
@isActive bit

AS
BEGIN
    SET NOCOUNT ON;

    UPDATE MyTable
    SET isActive = @isActive, updatedate = GETDATE()    
    WHERE region = @region 
    AND (isonumber = @isoNum or @isoNum IS NULL AND isonumber IS NULL)

END

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM