I’m attempting to pull data out of several databases which are identical for the most part except for the db names. The following script works except for the output is in 12 separate results.
Caveat is that this would have to be repeatable for all the tables and schemas in those databases
Anyone has a workaround to solve this?
--------------------------------------------------------------------------------------
DECLARE @DBMonth AS INT = 1 -- SET MONTH (January)
DECLARE @DBYear AS INT = 2012 -- SET YEAR ***THE OLDEST YEAR AVAILABLE***
DECLARE @DB AS VARCHAR(255) = 'TranHist1' -- DATABASE NAME
DECLARE @DBSchema AS VARCHAR(255) = '.dbo' -- SCHEMA
DECLARE @DBTable AS VARCHAR(255) = '.Tabl_1' -- TABLE
DECLARE @Sql VARCHAR(250) -- HOLDS THE SQL STATMENT TO BE EXCUITED
WHILE @DBMonth BETWEEN 01 AND 12
AND @DBYear = 2012
BEGIN
SELECT @Sql = 'select top 10 * from ' + @DB
+ right('00' + ltrim(str(@DBMonth)), 2)
+ CONVERT(NVARCHAR(4), @DByear)
+ @DBSchema + @DBTable
BEGIN
EXEC (@Sql)
SET @DBMonth += 1; --INCREMENT MONTH COUNTER
IF (
@DBMonth NOT BETWEEN 1 AND 12
OR @DBYear NOT BETWEEN 2012 AND 2013
)
BREAK
ELSE
CONTINUE
END
END
↧