I have a table, tblDocs that has a few columns:
DocName varchar(50)
DocLocation int
Active int
DocID int
All entries in the table have a DocName and DocLocation. Active and DocID are blank.
What I need to do is for each row in tblDocs I need to check the value of DocLocation and based on that value I update tblDocs, setting the Active and DocID columns. I was thinking that I would use a CASE WHEN but I’m not sure – I dont know sql very well. If i were using c# or vb.net it would be the equivalent of a for each loop.
foreach row as DBRow in tblDocs
row.active = 1
row.docID = ID
next
How do you do this for SQL Server 2005?
UPDATE
From a couple of responses below it sounds like I will use an UPDATE Statement. So I could accomplish this by doing something like
UPDATE tblDocs
SET docID =
CASE DocLocation
WHEN 1 THEN --do stuff
WHEN 3 THEN --do other stuff
and this would go through ALL the rows of tblDocs and update the DocID to be based on DocLocation?
The trick here is that C# and VB.Net (and javascript, c++, and any other language you’re likely used to) are procedural languages. SQL is a declarative language. You describe operations that act on an entire set a time.
With that in mind, you want to describe an operation that will
"check the value of DocLocation and based on that value I update tblDocs, setting the Active and DocID columns."And to do that you use anUPDATEquery and case statements:Just a note that this sample also demonstrates how you can use the CASE statement to unset a value (set it back to null) or even leave it alone by assigning it itself. It’s also worth nothing that if you really expect to leave a lot of the values alone, you should do that with a WHERE clause instead.