Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Query generating column names (sorta pivot questio

Author  Topic 

cored
Starting Member

2 Posts

Posted - 2011-10-03 : 19:49:46
Hi-

I can't change the database, and I have a number of tables I often need to query that are set up so that I need to join on data stored in multiple columns in the parent table rather than one relation column in the child table.

Example:
Table1
ID, Parameter_0, Parameter_1, Parameter_2, etc.

Table2
ID (This is what I want to find in Parameter_*)

I can type it all out in a lengthy WHERE, but I'm wondering if I can make a subquery, and do something like:

SELECT
(Set a variable
Create a column name like "Parameter_" & variable
Increment the variable
Loop until I get a set number of column names)
FROM Table1
WHERE etc.

From there I'll have the row of data and can pivot it or whatever.

Thanks.

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2011-10-03 : 19:53:45
It would require dynamic SQL and would not be advisable. You can easily generate code from SSMS though.

Tara Kizer
Microsoft MVP for Windows Server System - SQL Server
http://weblogs.sqlteam.com/tarad/

Subscribe to my blog
Go to Top of Page

cored
Starting Member

2 Posts

Posted - 2011-10-05 : 10:35:56
Thanks. After scouring the web for what I thought would be a pretty simple deal, it looks like not so much, so I think I'll just type them out.

And try to find who built the tables that way and why...
Go to Top of Page
   

- Advertisement -