Statistics

Total Posts: 34
This Year: 0
This Month: 0
This Week: 0
Comments: 174


RSS 2.0   SocialTwist Tell-a-Friend


Admin

Sign In

Navigation


Recent Posts


On this page....

How to swap data between two columns of a table in SQL Server?

Archives

 Full Archives By Category
 2007 Calendar View
<August 2009>
SunMonTueWedThuFriSat
2627282930311
2345678
9101112131415
16171819202122
23242526272829
303112345

Categories

CDOSYS (1) Classic ASP (10) Command Line (2) Databases (16) Excel (1) HTML (1) IIS (10) Indexing Service (1) Internet Explorer (7) Media Streaming (1) MS.Net (2) SQA (7) SQL Server (16) Windows OS (2)

Blogroll - Fav Blogs


Acknowledgments

DasBlog Theme Design by: Tom Watts
E-mail: Send mail to the author(s)
Theme Image by: dreamLogic

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

Technology Blog

When we talk about swapping of data between two columns of a table in SQL Server, most of us think of writing SQL scripts in Stored Procedure to achieve it. Well, is it really required? Can a one line statement be written to swap data between two columns in a table? The answer is yes. In this article I cover a simple technique to swap data between two columns of a table.

Consider a table by name "MyTable" having 3 fields RecID as Integer, ColValue01 as VarChar of 50 and ColValue02 as VarChar of 50; as written in the below SQL statement
CREATE TABLE [MyTable] (RecID INT, ColValue01 VARCHAR(50), ColValue02 VARCHAR(50))

Now due to some program error, the data which was suppose to go to ColValue02 has gone to ColValue01 and Vise-a-Versa. We need to swap the data between the two columns, run the below script to achieve the same.

#Option 01: The process is simple, first declare a temp variable, move column 2 value to temp variable, then move column 1 value to column 2 and finally move temp variable value to column 2.

DECLARE @MyTemp AS VARCHAR(50)
UPDATE [MyTable] SET @MyTemp = ColValue02, ColValue02 = ColValue01, ColValue01 = @MyTemp))


#Option 02: The same result can be achieved without using a temp variable by simply cross assigning the column names as shown the scrip below.
UPDATE [MyTable] SET ColValue01 = ColValue02, ColValue02 = ColValue01))

Note: The column data can be exchanged between two or more columns of same data type only.