Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2000 Forums
 SQL Server Development (2000)
 Tip: updating arbitrary columns using SP

Author  Topic 

aiken
Aged Yak Warrior

525 Posts

Posted - 2002-05-05 : 16:43:21
This probably isn't news to anyone, but I thought I'd document a nifty way of allowing a single stored procedure to update an arbitrary number of columns at once, without disturbing columns that don't need to be updated.

Given a table:

USERS
-----
user_id int IDENTITY
field1 int
field2 varchar(200)
field3 datetime
.
.
.

Here's a stored procedure:


CREATE PROCEDURE p_UpdateUser (@iUsers int,@f1 int=NULL,@f2 varchar(200)=NULL,@f3 datetime=NULL) AS
set nocount on
update users set field1=IsNull(@f1,field1),field2=IsNull(@f2,field2),field3=IsNull(@f3,field3)


Now, an ASP page or other app can update any combination of columns using a single stored procedure, without resorting to dynamic SQL.

Examples:

p_UpdateUser @iUsers=1,@f2='test'

p_UpdateUser @iUsers=1,@f1=47,@f3='5/5/2002 17:00:00'


Probably nothing special or new, but I thought it was nifty. You could do the same thing with COALESCE rather than ISNULL, of course, but unless there's some advantage ISNULL is more intuitive to read.

Cheers
-b

No problem! -robvolk

Edited by - robvolk on 05/05/2002 17:26:06

aiken
Aged Yak Warrior

525 Posts

Posted - 2002-05-05 : 16:43:59
Argh! Wrong forum! I meant to post this over in Developer.

Sorry!
-b

Go to Top of Page
   

- Advertisement -