I am writing a stored procedure to update a transaction tab开发者_Python百科le.
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
did you try using ISNULL ( check_expression , replacement_value )
精彩评论