是的,这可以通过使用动态SQL来实现。我不能测试它,但或多或少它应该按您指定的方式工作。它将在屏幕(消息区)上显示正在运行的语句,您可以调整select@sql=…根据您的方便,直到您找到正确的声明:
ALTER procedure [dbo].[sp_RequestCategoryCount]
@StDate1 date,
@EnDate1 date,
@StDate2 date,
@EnDate2 date
AS
BEGIN
DECLARE @SQL AS NVARCHAR(MAX);
SELECT distinct RQ.request_category
into #ReqCat
FROM ( Select distinct request_category from [VerInt_OneViewServiceReq]
UNION ALL
Select distinct request_category from [VerInt_OneViewServiceReq2]
) RQ
Select
'1' as Iteration,
request_category,
Sum(1) as Record_Count
INTO #Iter1
from [VerInt_OneViewServiceReq]
where request_created_dt between @StDate1 and @EnDate1
group by request_category
--UNION ALL
Select
'2' as Iteration,
request_category,
Sum(1) as Record_Count
INTO #Iter2
from [VerInt_OneViewServiceReq2]
where request_created_dt between @StDate2 and @EnDate2
group by request_category
--order by Iteration, request_category ASC
SELECT @SQL = '
Select RC.request_category,
IT1.Record_Count as ['+CONVERT(VARCHAR(10), @StDate1)+'_to_'+CONVERT(VARCHAR(10), @EnDate1)+'],
IT2.Record_Count as ['+CONVERT(VARCHAR(10), @StDate2)+'_to_'+CONVERT(VARCHAR(10), @EnDate2)+']
from #ReqCat RC
LEFT JOIN #Iter1 IT1
ON IT1.request_category = RC.request_category
LEFT JOIN #Iter2 IT2
ON IT2.request_category = RC.request_category'
-- Debug purposes
PRINT @SQL;
EXEC sp_ExecuteSQL @SQL;
Drop Table #ReqCat
Drop Table #Iter1
Drop Table #Iter2
END