May 5, 2010 at 10:39 am
I need to create a stored procedure or query that will dynamically create columns from data in a column.
i.e.
mytable
field1
tom, gary, Thomas, bob
alex, bill, bob, dennis, gary
I want to run a query/sproc that will read the first row and create 4 columns and each column will have the name in it. The second row will then create the 5th column and insert all names in the corresponding columns.
i.e.
Start with this:
Field1
tom, gary, Thomas, bob
alex, bill, bob, dennis, gary
Run the query/sproc and then get this:
Field1name1name2name3name4name5
tom, gary, Thomas, bobtomgaryThomasbob
alex, bill, bob, dennis, garyalexbillbobdennisgary
May 5, 2010 at 2:33 pm
Why do you want to do it dynamic?
Based on your sample data I would use a string split function to separate the names (the TallyTable article referenced in my signature has an example of such a function). Based on that I would either use a CrossTab (known max. number of names) or a DynamicCrossTab concept to create and populate the table you're looking for. Both articles are referenced in my signature as well.
May 5, 2010 at 4:04 pm
The Dynamic part is for the creation of the fields. It starts out with the 1 column with the string of names (comma delimited).
May 5, 2010 at 4:17 pm
alex abenitez (5/5/2010)
The Dynamic part is for the creation of the fields. It starts out with the 1 column with the string of names (comma delimited).
Do you know how many field you'll end up with? Will it always be five or less?
May 5, 2010 at 6:00 pm
I don't know how many fields it will be but I expect it to be less than 30.
May 8, 2010 at 4:46 am
alex abenitez (5/5/2010)
I don't know how many fields it will be but I expect it to be less than 30.
Did you have the time to read the articles I mentioned in my first reply? Seems to be that DynamicCrossTab is the way to go.
Or, alternatively, do it in the application layer.
May 8, 2010 at 5:48 am
Yes, working on it. I got side tracked and got pulled away on a critical project. I will follow up in a week. Thanks for your help.
May 8, 2010 at 7:58 pm
alex abenitez (5/5/2010)
The Dynamic part is for the creation of the fields.
Heh... we know that, Alex. How will it be used? I ask because that's a large key to how to do this.
I'm glad you got it working but I'd still be interested in know the "why" and what you did to solve it. We might be able to make it a wee bit faster (or not).
--Jeff Moden
Change is inevitable... Change for the better is not.
Viewing 8 posts - 1 through 7 (of 7 total)
You must be logged in to reply to this topic. Login to reply