October 3, 2006 at 7:44 am
Hi all,
I have a column named QuestionNodeTypeUID that contains ID's that point to a Lookup table. What I need to do is change the rows that have the column value of 6 to 5 and the rows that have the column value of 5 to 6.
Is it possible to perform this update in one simple query? I tried to use the CASE statement but the ELSE part of it cannot do tests (like in the WHEN).
(I can't use temp tables)
Thanks in advance.
Tryst
October 3, 2006 at 7:55 am
You should be able to use a CASE statement. Have a look at the example I cooked up below...
CREATE TABLE #test(QuestionNodeTypeUID INT NOT NULL,
description VARCHAR(50))
INSERT INTO #test (QuestionNodeTypeUID,description) VALUES (5, 'This should END up AS 6') INSERT INTO #test (QuestionNodeTypeUID,description) VALUES (5, 'This should END up AS 6') INSERT INTO #test (QuestionNodeTypeUID,description) VALUES (3, 'This should not change') INSERT INTO #test (QuestionNodeTypeUID,description) VALUES (6, 'This should END up AS 5') INSERT INTO #test (QuestionNodeTypeUID,description) VALUES (6, 'This should END up AS 5') INSERT INTO #test (QuestionNodeTypeUID,description) VALUES (5, 'This should END up AS 6')
SELECT * FROM #test
UPDATE #test
SET QuestionNodeTypeUID = CASE WHEN QuestionNodeTypeUID = 5 THEN 6
WHEN QuestionNodeTypeUID = 6 THEN 5
ELSE '' END -- You could add some error or something here for if something went wrong.... add a 'err' or something so that the update staement blows up and doesn't complete. Wrap it in a transaction so it rolls back etc...
WHERE QuestionNodeTypeUID BETWEEN 5 AND 6
SELECT * FROM #test
DROP TABLE #test
October 3, 2006 at 8:03 am
Tryst
Here's a way of doing it without a CASE statement
--DataCREATETABLE #MyTable (TableID int, QuestionNodeTypeUID int)
INSERTINTO #MyTable VALUES (1, 4)
INSERTINTO #MyTable VALUES (2, 5)
INSERTINTO #MyTable VALUES (3, 6)
--QueryUPDATE#MyTable
SETQuestionNodeTypeUID = QuestionNodeTypeUID - SIGN(2 * QuestionNodeTypeUID - 11)
WHEREQuestionNodeTypeUID IN (5, 6)
--ResultsSELECT* FROM #MyTable
John
October 3, 2006 at 9:59 am
Thanks for the replies guys.
John: That is a very neat way of doing it. So can that query be applied to all cases where you need to convert/switch values (so long as the values you need to switch are in the IN clause)?
Thanks
Tryst
October 3, 2006 at 10:10 am
Tryst
Yes, so long as it as simple as switching two values over. Obviously if the values were 13 and 28, say, then you'd need to think about how you would rewrite that update statement.
John
Viewing 5 posts - 1 through 4 (of 4 total)
You must be logged in to reply to this topic. Login to reply