简体   繁体   中英

SQL Server 2005 stored procedure

I am writing a stored procedure to update a transaction table.

I will be updating one transaction type at a time (shipment, receipt or disposal)

If I'm updating shipment, I will pass in a value, and leave the other two blank.

How can I write a stored procedure so that it only updates the field when the value I'm passing in is not NULL (or 0, whichever is easier), and leave the others as they were?

Here is where I am now:

CREATE PROCEDURE [dbo].[sp_UpdateTransaction] 
    -- Add the parameters for the stored procedure here
    @ID int,
    @disposalID int,
    @shipID int,
    @recID int,
as
begin
   update tblX
   set
     disposalID = COALESCE(@disposalID, disposalID)
     receiptID = COALESCE(@recID, receiptID)
     shipmentID = COALESCE(@shipID,shipmentID)
   where ID = @sID 
END 

COALESCE doesn't seem to work, as I keep getting errors, is there another function I can use to make this happen?

I'm getting:

Incorrect syntax near 'receiptID'.

I don't see why :(

Thank you!

The reason you are getting error could also be because you are missing ',' at end of each set .

update tblX
set
disposalID = COALESCE(@disposalID, disposalID),
receiptID = COALESCE(@recID, receiptID),
shipmentID = COALESCE(@shipID,shipmentID)
where ID = @sID

As an alternative, you can use ISNULL() assuming you are using SQL server.

what you can do is put each update statement inside an IF or a CASE statement. like:

IF @disposalid is not null:
     update tblX
     set disposalID = @disposalID

您是否尝试使用ISNULL ( check_expression , replacement_value )

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