Saturday, December 15, 2012

Swap Value In A Table Column

Introduction:  In This article we will see how to interchange the values of  a column in a table. Sometimes in our development cycle we may have to face a situation where we might have to interchange the values of a table column. SQL has provided us a very useful query for this purpose.

Example:  Suppose you have a Product table as below. And you have to swap the active field values i.e. True must be False and False must be True.

      ProductID           ProductName                                                                            Active





















































1ChaiTrue
2Chai SpecialTrue
3Aniseed SyrupTrue
4Chef Anton's Cajun SeasoningTrue
5Chef Anton's Gumbo MixFalse
6Grandma's Boysenberry SpreadTrue
7Uncle Bob's Organic Dried PearsTrue
8Northwoods Cranberry SauceTrue
9Mishi Kobe NikuFalse
10IkuraTrue

Use query stated below to swap the values.

UPDATE Products SET Active =
CASE Active
WHEN 1 THEN 0
WHEN 0 THEN 1
END


Result:

ProductID       ProductName                                                                           Active





















































1ChaiFalse
2Chai SpecialFalse
3Aniseed SyrupFalse
4Chef Anton's Cajun SeasoningFalse
5Chef Anton's Gumbo MixTrue
6Grandma's Boysenberry SpreadFalse
7Uncle Bob's Organic Dried PearsFalse
8Northwoods Cranberry SauceFalse
9Mishi Kobe NikuTrue
10IkuraFalse