CREATE FUNCTION NaviTable ( @db varchar(50), @company varchar(50), @table varchar(50), @alias varchar(50) ) RETURNS varchar(200) AS BEGIN DECLARE @retval varchar(200) SET @retval = ' [' + @db+ '].[dbo].['+@company +'$' + @table +'] ' + @alias + ' ' RETURN @retval END CREATE PROCEDURE SalesByYearMonth @year integer, @month integer, @company varchar(50), @database varchar(50) as declare @prevyear integer declare @cleThisYear varchar(200) declare @cleLastYear varchar(200) set @prevyear = @year-1 set @cleThisYear = dbo.NaviTable(@database, @company, 'Cust_ Ledger Entry', 'cleThisYear') set @cleLastYear = dbo.NaviTable(@database, @company, 'Cust_ Ledger Entry', 'cleLastYear') exec( ' select (select sum(cleThisYear.[Sales (LCY)]) from' + @cleThisYear + ' where datepart(yyyy, cleThisYear.[Posting Date])= ' + @year +' and datepart(month,cleThisYear.[Posting Date])<=' + @month + ' ) as SalesThisYear, (select sum(cleLastYear.[Sales (LCY)]) from' + @cleLastYear + ' where datepart(yyyy, cleLastYear.[Posting Date])=' + @prevyear +' and datepart(month,cleLastYear.[Posting Date])<=' + @month+ ') as SalesLastYear ') -- end of exec