Wednesday, March 28, 2012

How Do I Add 1 to a Field?

I have a Table: Thread

There are 2 relevant fields: ThreadID and Counter (integer).

I want a Stored Procedure that will get a record based on ThreadID and will add 1 to the counter.

I know how to do this as 2 stored procedures (one to get the current value of the counter and a second procedure to write the new value).

There must be a better way to do it as one procedure though.

Any suggestions?

Thanks,

Chris

You can do this in a number of ways. get the number and add the 1 at the application layer. or even as simple as

SELECT counter+1

FROM Thread

WHERE Threadid = @.Threadid

|||

The example you give will return a number 1 larger, but I also need to have that new number written into the data.

Can I do that with 1 stored procedure?

Chris

|||

Chris Messineo:

I want a Stored Procedure that will get a record based on ThreadID and will add 1 to the counter.

Thats what you wanted right?

|||

I'm sorry if my question is confusing.

I need to get the new value, but I also need to set that value in the db. I believe your solution will just get me the new value.

Does that make sense?

Chris

|||

do an UPDATE then. You can write a proc that will do the update and return the value. you can either return using an OUTPUT parameter or a SELECT statement.

No comments:

Post a Comment