0

I have a really inefficient sql script that takes the following table, and populates val2 using a cursor. I want to be able to update all of the val2 values with a single update, but val2 is calculated using val1 for each row.

val1: 1, val2 0
val1: 2, val2 0 
val1: 3, val2 0
val1: 4, val2 0
val1: 5, val2 0

So I imagine, you'd have something like this:

UPDATE Table SET val2 = (some code based on val1 for each row)

How can I write this into a single line of sql?

1
  • I've given you my best guess, but you'll need to be more specific about the code you want if you want a more complete answer. Commented Dec 30, 2011 at 19:13

1 Answer 1

5
update table set val2 = val1 + 1

Works just like that! If you have some set of codes that you want to have applied by a case statement:

update table set
    val2 = 
        case 
            when val1 = 1 then 'One'
            when val1 = 2 then 'Two'
            when val1 = 3 then 'Three'
            else 'Something something'
        end
Sign up to request clarification or add additional context in comments.

2 Comments

I see, so if you just use val1 in the set val2 statement, it will assume it is the val1 in the same row. Thanks :)
@sooprise - yes, in much the same way as you can combine values from multiple columns in a select statement

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.