|
-
Nov 28th, 2008, 06:23 AM
#1
Thread Starter
Lively Member
[RESOLVED] How to swap values in SQL Server 2008!
Hi…
I’m wondering if possible to swap values in database column using update script in sql server 2008!!
In this case I want to update all rows in one column by a single script.
For example if I have:
Table name: dbo.ABC
Column name: FGH
Rows value:
XXX 111 ZZZ 222
XXX 333 ZZZ 444
XXX 555 ZZZ 666
XXX 777 ZZZ 888
Rows value after swap update:
ZZZ 222 XXX 111
ZZZ 444 XXX 333
ZZZ 666 XXX 555
ZZZ 888 XXX 777
If possible ! how the script will be?
Regards…
-
Nov 28th, 2008, 06:52 AM
#2
Re: How to swap values in SQL Server 2008!
Im not quite clear about the question. Is there one column with spaces in it or 4 separate columns? Assuming the latter it's quite easy:-
Code:
Update ABC
Set Col1 = Col3,
Col2 = Col4,
Col3 = Col1,
Col4 = Col2
The best argument against democracy is a five minute conversation with the average voter - Winston Churchill
Hadoop actually sounds more like the way they greet each other in Yorkshire - Inferrd
-
Nov 28th, 2008, 07:07 AM
#3
Thread Starter
Lively Member
Re: How to swap values in SQL Server 2008!
 Originally Posted by FunkyDexter
Im not quite clear about the question. Is there one column with spaces in it or 4 separate columns? Assuming the latter it's quite easy:-
Code:
Update ABC
Set Col1 = Col3,
Col2 = Col4,
Col3 = Col1,
Col4 = Col2
Thanks for reply FunkyDexter
it's one column and the values in this column are:
XXX 111 ZZZ 222
XXX 333 ZZZ 444
XXX 555 ZZZ 666
XXX 777 ZZZ 888
* there are spaces between the values in this column
-
Nov 28th, 2008, 07:14 AM
#4
Re: How to swap values in SQL Server 2008!
Code:
update ABC
set FGH = SUBSTRING(FGH, 9, 7) + ' ' + SUBSTRING(FGH, 1, 7)
-
Nov 28th, 2008, 07:34 AM
#5
Thread Starter
Lively Member
Re: How to swap values in SQL Server 2008!
Last edited by HOTFIX; Nov 28th, 2008 at 07:38 AM.
-
Nov 28th, 2008, 07:42 AM
#6
Re: How to swap values in SQL Server 2008!
The SUBSTRING function extracts the specified number of characters from the string.
The syntax is:
SUBSTRING ( expression, start, length)
You could google for SUBSTRING T-SQL command to know more about this function.
So the first substring extracts 7 characters from the field FGH starting from the 9th character. The second substring extracts 7 characters from the field FGH starting from the 1st character.
So this makes it (7 characters starting from 9th character) + (one space) + (7 characters starting from 1st character)
Hope you got it.
Pradeep
-
Nov 28th, 2008, 07:54 AM
#7
Thread Starter
Lively Member
Re: How to swap values in SQL Server 2008!
Thanks Pradeep for info about SUBSTRING function...
Best Regrads...
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|