SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 General SQL Server Forums
 New to SQL Server Administration
 Using Query results as sources
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

ob61887
Starting Member

USA
1 Posts

Posted - 10/12/2012 :  23:56:17  Show Profile  Reply with Quote
Hello,

This is my first time posting so sorry if this is hard to read.

I am attempting to use a query to select tables and columns as the source for another script. I would use the below query to select the Tables and Columns I am looking for, and am curious if it is possible for another query to use the tables.columns retrieved here as its select and from sources.

select
a.TABLE_NAME,
b.COLUMN_NAME
from
INFORMATION_SCHEMA.TABLES as a
join INFORMATION_SCHEMA.COLUMNS as b on a.TABLE_NAME = b.TABLE_NAME
where
b.COLUMN_NAME like '%parameter'
order by 'TABLE_NAME', 'COLUMN_NAME'

So if this brought back:
TABLE_A1 COLUMN_1A
TABLE_A2 COLUMN_2A
TABLE_A3 COLUMN_3A

I would want the query to perform like:

select
COLUMN_1A
from
TABLE_A1
union
select
COLUMN_2A
from
TABLE_A2
union
select
COLUMN_3A
from
TABLE_A3

malpashaa
Constraint Violating Yak Guru

Saudi Arabia
260 Posts

Posted - 10/13/2012 :  00:26:00  Show Profile  Reply with Quote
Try something like this:

DECLARE @stmt VARCHAR(MAX) = STUFF((SELECT ' UNION' +
                                           ' SELECT ' + B.COLUMN_NAME +
                                           ' FROM ' + A.TABLE_SCHEMA + '.' + A.TABLE_NAME
                                      FROM INFORMATION_SCHEMA.TABLES AS A
                                           INNER JOIN
                                           INFORMATION_SCHEMA.COLUMNS AS B
                                           on A.TABLE_NAME = B.TABLE_NAME
                                     WHERE B.COLUMN_NAME like '%parameter'
                                     ORDER BY A.TABLE_NAME, B.COLUMN_NAME
                                     FOR XML PATH('')), 1, LEN(' UNION'), '');

EXECUTE(@stmt);




For us, there is only the trying. The rest is not our business. ~T.S. Eliot

Muhammad Al Pasha
Go to Top of Page
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.05 seconds. Powered By: Snitz Forums 2000