Skip to content
Advertisement

How can I not send Null to database while using Update

If i need to just update one column do i have to give other column previous value or i can just give give the column i need to change and not null values to update in database .. here is procedure code what can i do to this procedure so that i can just need to insert the value i want to update …

 ALTER procedure [dbo].[Customer_update] 
( @Id int,
@Firstname nvarchar(40)=,
@Lastname nvarchar(40)=,
@City nvarchar(40)=null,
@Country nvarchar(40)=null,
@Phone nvarchar(20)=null

)
as 
begin 
update Customer set FirstName=@Firstname,LastName=@Lastname,City=@City,Country=@Country,Phone=@Phone where Id=@Id 
end 

Advertisement

Answer

You almost have it and as Alex K pointed out in the comment above, the most elegant way to handle optional updates is to allow null parameters and update what is sent over.

ALTER PROCEDURE [dbo].[Customer_update] 
    (@Id INT,
     @Firstname NVARCHAR(40) = NULL,
     @Lastname NVARCHAR(40) = NULL,
     @City NVARCHAR(40) = NULL,
     @Country NVARCHAR(40) = NULL,
     @Phone NVARCHAR(20) = NULL)
AS
BEGIN
    UPDATE Customer 
    SET FirstName = ISNULL(@Firstname, FirstName)... 
    WHERE Id = @Id 
END

In order to use this in client code with nullable fields, simply omit the parameter altogether or let nulls pass through (one caveat to this is when you really need to set the field to null in which case the field should probably not be nullable. Then you can implicitly send a null over and the field will be set to the proper value)

Nullable fields allow you to omit parameters from a stored procedure call and still perform the operation. This is useful when you need make changes and do not want to impact existing applications, as long as the nullable fields are not required.

Are you asking about Insert/Update in one operation?

Some people do “upserts”. I personally do not like having one operation for insert/updates. I feel the client should already know what operation should be performed, also, having one update and one insert procedure makes the procedures more transparent and easier to auto generate.

However, if that is what you were asking then you would create a procedure similar to the one below:

ALTER PROCEDURE [dbo].[Customer_update] 
    (@Id INT = NULL,
     @Firstname NVARCHAR(40) = NULL,
     @Lastname NVARCHAR(40) = NULL
     @City NVARCHAR(40) = NULL
     @Country NVARCHAR(40) = NULL
     @Phone NVARCHAR(20) = NULL)
AS
BEGIN
    IF (@Id IS NULL) 
    BEGIN
        INSERT INTO Customer...
        SET @ID = @@SCOPE_IDENTITY
    END 
    ELSE BEGIN
        UPDATE Customer 
        SET FirtName = ISNULL(@FirstName, FirstName)
        WHERE Id = @Id
    END

    SELECT * 
    FROM Customer 
    WHERE Id = @Id
END
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement