views:

65

answers:

1

I would like to call an "update" stored procedure which won't necessarily include all columns. There is probably a better way to handle this.... As you can see, if I do not pass in the column parameters their value is NULL. Then, using the ISNULL, I set the columns either to their new values or their existing values.

CREATE PROCEDURE [dbo].[spUpdateTable] 

 @pPKID bigint = NULL,
 @pColumn1 int = NULL, 
 @pColumn2 int = NULL

AS
BEGIN

 SET NOCOUNT ON;

 UPDATE
    TableName
 SET
    [Column1] = ISNULL(@pColumn1,[Column1]),
    [Column2] = ISNULL(@pColumn2,[Column2])

 WHERE
    [PKID] = @pPKID
END
+2  A: 

This is basically the same thing that the transactional replication stored procedures do when updating a table on a subscriber. If Microsoft does it themselves, it must be safe, right? :-)

Seriously, my primary concern here would be any update triggers that might exist on the table. You'd want to understand the impact of potentially firing those triggers on what could be a non-change. Otherwise I think your technique is fine.

Joe Stefanelli
Good reminder about update triggers. While I deliberately was not using any in this DB I can definitely see that being an obstacle for certain tables in other projects. Do you have any suggestions for an alternate method in cases where update triggers do exist? Furthermore, should I be concerned about such triggers in replicated DB's?
Matthew PK
If you needed an alternative, you could test each parameter and construct the update statement into a string that you'd execute as dynamic SQL. Here's the obligatory link to [The Curse and Blessings of Dynamic SQL](http://www.sommarskog.se/dynamic_sql.html). As for triggers in a replicated DB, that's probably a whole separate discussion. As a simple example, if you're replicating tables A and B, and A has a trigger that inserts into B, you'd certainly want to disable that same trigger on the subscriber.
Joe Stefanelli
Makes perfect sense. I've read that bit on dynamic SQL many times before (and I like to avoid dynamic SQL whenever possible)
Matthew PK