July 9, 2009 at 5:19 pm
Hi,
I am a novice to T-SQL and I believe I am not fully harnessing the power of SQL when I find my code full of loops and conditional statements, I am hoping you folks can point me in the right direction.
Here is the table I have,
CREATE TABLE tableA
(
id INT primary key,
year CHAR(10)
data CHAR(100) )
What I am trying to do is to add a constant number to values of the year column for all matching rows. e.g. change all the years to 4 year later by adding 4 to the year column.
Is there a easy way to do this instead of pulling each row out and adding 1 to every row?
Thanks in advance for any help
July 9, 2009 at 5:24 pm
UPDATE dbo.tablea SET Year = CONVERT( int, Year ) + 1
I am counting on a number of facts here, I converted it to an integer, it will convert it back to a varchar for me. I also count on the fact that I want to change ALL records. If I don't I need a WHERE clause to restrict it.
Clear?
CEWII
July 9, 2009 at 5:47 pm
I added a where clause and it worked perfectly, I'm sure glad to throw out all the control statements and loops. Thanks a lot Elliott!
July 9, 2009 at 6:00 pm
You are welcome, this is called a SET based operation, you performed the operatio on a whole set instead RBAR (Row-by-agonizing-row)..
CEWII
July 10, 2009 at 6:59 am
That being said, you should be careful about doing an update on a large number of rows, in a production database, since the operation will lock the rows that are being updated, and other operations against those rows will timeout until the update is complete. In the case of a simple update like yours, it's probably not an issue, but if your update would take a long time to run, you could risk losing other data in the process. If that's the case, then the approach of updating one record at a time is probably the better one, despite looking ugly.
July 19, 2009 at 9:50 pm
kramaswamy (7/10/2009)
If that's the case, then the approach of updating one record at a time is probably the better one, despite looking ugly.
Ummm... no... not if it's done correctly. Correctly means that you know the updates are prequalified and will work without failure.
--Jeff Moden
Change is inevitable... Change for the better is not.
Viewing 6 posts - 1 through 5 (of 5 total)
You must be logged in to reply to this topic. Login to reply
This website stores cookies on your computer.
These cookies are used to improve your website experience and provide more personalized services to you, both on this website and through other media.
To find out more about the cookies we use, see our Privacy Policy