troubleshooting Question

using a dynamic database name over a linked server

Avatar of qube09
qube09 asked on
Microsoft SQL Server
7 Comments1 Solution241 ViewsLast Modified:
There two questions here.
I need to query tables over a linked server. The tables all have the following structure
with a number that is the month of the year.
things_1,things_2,things_3.... things_10,things_11,things_12

the basic sql used is of the form (things_n corresponds to 1-12 as above)
select a,b,c from remoteserver.database.dbo.things_n
where convert(char(12),local_time = convert(char(12),getdate()-1)
and item in('a','b','c','d','e','f','g')
order by local_time

I should add that each of the remote databases are quite large.

question 1
I guess that I could construct a dynamic sql based on the desired month particularly if it was local but is there a better method short of a list of If statements?

question 2
Admittedly I have tried a dynamic sql but can not get it to work

declare @sql nvarchar(4000),
             @tblname nvarchar(9)
select @m = 1
select @tblname = 'things_' + @m
set @sql = 'select a,b,c from remoteserver.database.dbo.[' + @tblname + ']
where convert(char(12),local_time = convert(char(12),getdate()-1)
and item in('a','b','c','d','e','f','g')
order by local_time'

Do you have an opinion or alternative for question 1?
What is the correct format for question 2?

thanks
Join the community to see this answer!
Join our exclusive community to see this answer & millions of others.
Unlock 1 Answer and 7 Comments.
Join the Community
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 7 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros