我有一个存储过程,我想使其动态化,以便它可以处理不同的输入。除了以下内容外,我已经弄清楚了大部分动态过程。
有人可以告诉我如何编写这部分才能在动态过程中使用它吗?我只需要在每个变量'+
之前和之后放置吗?+'
INSERT INTO @temp
(
dateRange
)
SELECT @date0
UNION ALL
SELECT @date1
UNION ALL
SELECT @date2
UNION ALL
SELECT @date3
UNION ALL
SELECT @date4
UNION ALL
SELECT @date5
编辑: 整个查询仅供参考。在我做这个动态之前它是正确的,所以我的猜测是我这里有一些丢失或不需要的引号或任何其他写作错误。另外,我不确定最后一个嵌套查询中的 Where 条件是否正确写入是动态的。
ALTER PROCEDURE [dbo].[FetchHistoryCombined]
@selection nvarchar(100),
@date0 nvarchar(20),
@date1 nvarchar(20),
@date2 nvarchar(20),
@date3 nvarchar(20),
@date4 nvarchar(20),
@date5 nvarchar(20)
AS
BEGIN
SET NOCOUNT ON;
BEGIN
DECLARE @sql nvarchar(max)
SET @sql = N' DECLARE @temp AS TABLE
(
dateRange nvarchar(20)
)
DECLARE @temp2 AS TABLE
(
ranking int,
item nvarchar(100),
volume int
)
INSERT INTO @temp
(
dateRange
)
SELECT ' + @date0 + '
UNION ALL
SELECT ' + @date1 + '
UNION ALL
SELECT ' + @date2 + '
UNION ALL
SELECT ' + @date3 + '
UNION ALL
SELECT ' + @date4 + '
UNION ALL
SELECT ' + @date5 + '
INSERT INTO @temp2
(
ranking,
item,
volume
)
SELECT Top 10 RANK() OVER(ORDER BY COUNT(*) desc, ' + @selection + ') [Rank],
' + @selection + ',
COUNT(*) AS volume
FROM LogEsc
WHERE dateEsc LIKE ''' + @date0 + '%''
AND EID LIKE ''PE%''
GROUP BY ' + @selection + '
ORDER BY volume desc, ' + @selection + '
SELECT
(
SELECT A.item
FROM @temp2 A
ORDER BY A.ranking, A.item
FOR XML PATH(''''), ELEMENTS, TYPE
) AS top10,
(
SELECT B.dateRange,
(
SELECT C.item,
(
SELECT COUNT(*) AS volume
FROM LogEsc D
WHERE D.' + @selection + ' = C.item
AND D.EID LIKE ''PE%''
AND D.dateEsc LIKE B.dateRange + ''%''
FOR XML PATH(''''), ELEMENTS, TYPE
)
FROM @temp2 C
ORDER BY C.ranking, C.item
FOR XML PATH(''''), ELEMENTS, TYPE
) AS [dateRange/items]
FROM @temp B
FOR XML PATH(''''), ELEMENTS, TYPE
) AS history
FOR XML PATH(''ranking''), ELEMENTS, TYPE, ROOT(''ranks'')'
EXEC(@sql)
END
END
非常感谢,迈克。