update multiple fields in SQL

0

I am trying to update my table in SQL 2012 where the CategoryNumber values should be correspondant for the below name values but it seems that my syntax is wrong.

Update mytable
SET mytable.CategoryNumber IN ('02','05','10')
where mytable.name IN ('peter','michael','ralf')

Scorpion99

Posted 2015-11-05T17:17:53.947

Reputation: 1 023

You mention your syntax is wrong. You don't indicate the reason you believe that to be the case. – Ramhound – 2015-11-05T17:29:05.820

because I got an error when I tried too. – Scorpion99 – 2015-11-05T17:30:31.003

1That was my very subtle hint that you should update the question to include the error message. – Ramhound – 2015-11-05T17:32:33.267

Answers

1

IN is an operator that defines a set of values, thus it's treated like an unordered list. You cannot do that in the manner you are trying to. I'd suggest doing it one by one:

Update mytable
SET mytable.CategoryNumber = '02'
where mytable.name = 'peter';

Update mytable
SET mytable.CategoryNumber = '05'
where mytable.name = 'michael';

Update mytable
SET mytable.CategoryNumber = '10'
where mytable.name = 'ralf';

nKn

Posted 2015-11-05T17:17:53.947

Reputation: 4 960

but actually I have more than 300 values to update. – Scorpion99 – 2015-11-05T17:24:48.607

You can create an input file where each line has a CategoryNumber and a name, and iterate over so on each loop iteration the UPDATE statement is called with this pair of values. – nKn – 2015-11-05T17:26:33.123

2@Scorpion99 - You make no mention of that in your question. – Ramhound – 2015-11-05T17:28:39.650

how will I be able to read from this file? – Scorpion99 – 2015-11-05T17:31:17.923

@Scorpion99 - There are multiple ways. What have you tried? – Ramhound – 2015-11-05T17:33:12.093

Only the above method – Scorpion99 – 2015-11-05T17:44:05.910