I want to sum up values from several databases. At this moment I have three databases: SPA_PROD
, SPB_PROD
and SPC_PROD
.
My SQL query:
IF EXISTS (SELECT *
FROM sys.objects
WHERE object_id = OBJECT_ID(N'[dbo].[TESTSUM]')
AND TYPE IN (N'P',N'PC'))
DROP PROCEDURE [dbo].[TESTSUM]
GO
CREATE PROC TESTSUM
AS
BEGIN
DECLARE @dbName SYSNAME,
@ObjectSUM INT,
@d datetime
SET @d = '20141113'
DECLARE @SQL NVARCHAR(MAX)
DECLARE @DBObjectStats TABLE (
--DBName SYSNAME,
DBObjects INT)
DECLARE curAllDBs CURSOR FOR
SELECT name
FROM MASTER.dbo.sysdatabases
WHERE name like '%PROD'
ORDER BY name
OPEN curAllDBs
FETCH curAllDBs INTO @dbName
WHILE (@@FETCH_STATUS = 0) -- db loop
BEGIN
--SQL QUERY
SET @SQL = 'select @dbObjects = sum(doctotal) from ' +
QuoteName(@dbName) + '..Invoice
where DocDate = ''' + cast(@d as varchar(25)) + ''''
PRINT @SQL -- Debugging
EXEC sp_executesql @SQL, N'@dbObjects int output',
@dbObjects = @ObjectSUM output
INSERT @DBObjectStats
SELECT @ObjecSUM
FETCH curAllDBs INTO @dbName
END
CLOSE curAllDBs
DEALLOCATE curAllDBs
-- Return results
SELECT sum(DBObjects) [InvoiceSUM] FROM @DBObjectStats
END
GO
-- Execute stored procedure
EXEC TESTSUM
GO
And this work perfect and giving me right sum from all my DBs: 120 000$ ( 25 000 from SPA_PROD , 95 000 SPC_PROD and 0 (NULL) from SPB_PROD.
What I want to do:
I would like to parametrize, which allows me to choose date and databases. For example I want to choose SPA_PROD
and SPB_PROD
with date 2014-01-01 in another case I want all databases (SPA + SPB + SPC
with another date.
Is this even possible? Any ideas?
I can use everything what gives me SQL Server 2012 and T-SQL. Maybe this technology offers me easiest way to do this.
I am also using SAP Crystal Reports to convert SQL output into a beautiful report.
Sorry for my English and I tried to describe to you my problem as far as I could. If you want any additional information which helps u to help me -> ask me :).