简体   繁体   English

SQL Server 2005存储过程

[英]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? 如何编写存储过程,以便仅在我传递的值不为NULL(或为0,以较容易的一个为准)时才更新该字段,而保留其他字段不变?

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? COALESCE似乎不起作用,因为我不断收到错误消息,是否可以使用另一个功能来实现这一目标?

I'm getting: 我越来越:

Incorrect syntax near 'receiptID'. '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 . 出现错误的原因还可能是因为每个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. 作为替代,您可以使用ISNULL()并假设您正在使用SQL Server。

what you can do is put each update statement inside an IF or a CASE statement. 您可以做的是将每个更新语句放在IFCASE语句中。 like: 喜欢:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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