how to order columns dynamically

Declare @list varchar(100)
SET @list='A.[2001],A.[2002],A.[2003],B.[2001],B.[2002],B.[2003]'

Select @list

This is a sample, and my aim is to fetch columns as mentioned below :

-- Please help to get the below result by modifying the @list

Select 'A.[2001],B.[2001],A.[2002],B.[2002],A.[2003],B.[2003]'
more ▼

asked Apr 26, 2011 at 11:26 PM in Default

sunitha gravatar image

11 1 1 2

(comments are locked)
10|1200 characters needed characters left

1 answer: sort newest
It would be possible to use a tally table to split your string into a table and then re-order it so that it could be recompiled into a sorted string and then, from your question, I gather you want this to be used in a piece of dynamic TSQL. I am not sure this is the best way of handling what you want. Can you offer a bit of information about the rest of your project so that we can advise you better? Using TSQL to do complex string manipulation is never an efficient solution.
more ▼

answered Apr 27, 2011 at 03:15 AM

Fatherjack gravatar image

Fatherjack ♦♦
42.8k 75 79 108

(comments are locked)
10|1200 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

New code box

There's a new way to format code on the site - the red speech bubble logo will automatically format T-SQL for you. The original code box is still there for XML, etc. More details here.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here



Answers and Comments

SQL Server Central

Need long-form SQL discussion? SQLserverCentral.com is the place.



asked: Apr 26, 2011 at 11:26 PM

Seen: 730 times

Last Updated: Apr 27, 2011 at 01:52 AM