November 7, 2013 at 10:57 am
I’ve got an issue which has come up with enough regularity that I wanted to see if you knew of a cleaner solution than what I’ve been doing.
Here’s the scenario: I need to make some modification to a bunch of tables so I’m deriving a list in order to loop over it and perform some dynamic sql on them, but I only want the tables which have all of a given set of columns.
For example, I want all tables which contain InstrumentID, AssetClass and InstrumentType. I’ve been deriving that list like this:
use tempdb
go
--Set up two fake tables.
--#T1 should NOT show up in the list.
if object_id('tempdb.dbo.#T1') is not null drop table #T1
create table #T1
(
InstrumentID int,
AssetClass varchar(100)
)
--#T2 SHOULD show up in the list
if object_id('tempdb.dbo.#T2') is not null drop table #T2
create table #T2
(
InstrumentID int,
AssetClass varchar(100),
InstrumentType varchar(100)
)
--Derive list of tables which contain all three column
select t.name
from sys.tables t
inner join (select [object_id]
from sys.columns
where name in ('InstrumentID', 'AssetClass', 'InstrumentType')
group by [object_id]
having count(1) = 3) x
on t.[object_id] = x.[object_id]
where name like '#T[0-9]%'--This clause is just to filter out tempdb noise for the purposes of this example. It's not pertinent to the question
That works fine, but it just feels somewhat roundabout. Other than joining to sys.columns n times, is there a cleaner way to do this?
November 7, 2013 at 11:02 am
What about using INFORMATION_SCHEMA.COLUMNS view? it will give you the names of columns and tables.
Another option would be to use OBJECT_NAME() instead of querying sys.tables. 😉
November 7, 2013 at 11:08 am
November 7, 2013 at 11:11 am
November 7, 2013 at 11:13 am
Now I'm lost, I thought you just wanted to improve the query that ccame after "--Derive list of tables which contain all three column". Now I'm not sure what you're looking for.
November 7, 2013 at 11:18 am
Viewing 6 posts - 1 through 5 (of 5 total)
You must be logged in to reply to this topic. Login to reply