I am trying to access a table that is recreated in a new database each quarter. The table name stays the same but a new database name is created.
What I'm trying to achieve is using a select statement to include a variable that will look at a specific database with a range of Q317 to Q119. At the moment I have the select code set up but I have to reuse the same code but change the quarter for each database. Is there a more efficient way of doing this that I'm currently doing?
To make things trickier the Quarter value has to be a string not an integer.
As you can see I'm no expert and I've tried passing variables to the string which works but I can't successfully manage to have it iterate.
declare @tablename varchar(50)
set @tablename = '2'
EXEC('SELECT DISTINCT [GAELTACHT] FROM [EDB_Q' + @tablename + '18].[dbo].[POSTAL_ADDRESS]')
This is a simplified version of what I'm currently working with but just to demonstrate the databases I'm working with.
SELECT 'Q119' AS Quarter, Count(BUILDING_ID) FROM Towns.CITY_Q119
UNION ALL
SELECT 'Q418' AS Quarter, Count(BUILDING_ID) FROM Towns.CITY_Q418
UNION ALL
SELECT 'Q318' AS Quarter, Count(BUILDING_ID) FROM Towns.CITY_Q318
UNION ALL
SELECT 'Q218' AS Quarter, Count(BUILDING_ID) FROM Towns.CITY_Q218
UNION ALL
SELECT 'Q118' AS Quarter, Count(BUILDING_ID) FROM Towns.CITY_Q118
UNION ALL
SELECT 'Q417' AS Quarter, Count(BUILDING_ID) FROM Towns.CITY_Q417
Ideally, I would have 1 select statement that somehow iterates (but using string on integers) from between values 218 to 119. I don't know if what I'm asking for is even possible?
SysNameinstead ofVARCHAR(n)and useQUOTENAME()function too to quote the table name, note that you can't pass object names as a parameter. Also I suggest to usesp_execsqlinstead ofEXEC@TableNameisn't a table name, it's a database name, cause your table name is[POSTAL_ADDRESS].