I have around 50 different databases and inside each of these database there is a table with the same name. Now, I have a written a query which extract selected fields from the table, but I need to manually select the database. How do I write a query so that I can pass database name and pull the data from that table? Here is my code:
;WITH Review as (
select external_id as sponsorid, name as sponsorname, memberid, startdate, paidamt, code
from test.dev.sraw c left join client.dbo.sponsors s on c.customerid = s.external_id
where year(startdate) >2009 and startdate <> '0001-01-01' and startdate <> '1000-01-01'),
FinalDataCollection as (select sponsorid, sponsorname, count(*) as NbrOfClaims, count(distinct memberid) as NbrOfMembers, month(startdate) as mnth, year(startdate) as yr, sum(cast(paidamt as money)) as dollars, case when code > '0' then 'RX' else 'med' end as category, case when count(distinct memberid)> 0 then sum(cast(paidamt as money))/count(distinct memberid) else 0 end as costpm
from Review
group by sponsorid, sponsorname,year(startdate), month(startdate),case when code > '0' then 'RX' else 'med' end)
select * from FinalDataCollection
UPDATE #1
How do I replace ''SELECT top 5 * FROM '' + @db + ''.dbo.RAW'' of the following query with the above SQL query that start with ;WITH CTE
DECLARE @dbname NVARCHAR(200)
DECLARE @SQLString NVARCHAR (MAX)
SET @SQLString =
'DECLARE @db NVARCHAR(255)
DECLARE DB_CURSOR CURSOR LOCAL FAST_FORWARD FOR
SELECT db.name from sys.databases db WHERE db.name IN
(''A'',''B'',''C'' ) ORDER BY db.name
OPEN DB_CURSOR
FETCH NEXT FROM DB_CURSOR INTO @db
WHILE @@FETCH_STATUS = 0
BEGIN
EXEC(''SELECT top 5 * FROM '' + @db + ''.dbo.RAW'')
FETCH NEXT FROM DB_CURSOR INTO @db
END
CLOSE DB_CURSOR
DEALLOCATE DB_CURSOR'
EXEC sp_executesql @SQLString
Thank you