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 Administration
 Using Query results as sources

Author  Topic 

ob61887
Starting Member

1 Post

Posted - 2012-10-12 : 23:56:17
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

264 Posts

Posted - 2012-10-13 : 00:26:00
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
   

- Advertisement -