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....


Archives

 Full Archives By Category
 2007 Calendar View
<March 2010>
SunMonTueWedThuFriSat
28123456
78910111213
14151617181920
21222324252627
28293031123
45678910

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.

All comments require the approval of the site owner before being displayed.
Name
E-mail
(will show your gravatar icon)
Home page

Comment (Some html is allowed: a@href@title, b, blockquote@cite, em, i, strike, strong, sub, sup, u) where the @ means "attribute." For example, you can use <a href="" title=""> or <blockquote cite="Scott">.  

Enter the code shown (prevents robots):

Live Comment Preview