I have a stored procedure with the following piece. Now I would need the exact same procedure for several different scenarios where the only difference is that instead of "policy" I will refer to another column.

In order to avoid writing multiple stored procedures, is there a way I can use a variable input to define this specific column without having to make the whole procedure dynamic ?

INSERT INTO @temp
(       
            ranking,
            item,
            groupCount,
            groupName
)
SELECT      RANK() OVER(ORDER BY COUNT(*) desc, policy) [Rank],
            policy, 
            COUNT(*) AS groupCount,
            'currentMonth' AS groupName
FROM        Log_PE 
WHERE       CONVERT(DATE, dateEsc, 120) >= CONVERT(DATE, CONVERT(VARCHAR(6), GETDATE(), 112) + '01', 112)
GROUP BY    policy
ORDER BY    groupCount desc, policy

Many thanks for any help with this Tim.

有帮助吗?

解决方案

Yes, you can use dynamic SQL to achieve what you desire. First, create a variable to hold the name of the column that will vary. Then, create another variable to hold the dynamically generated query. Finally, use sp_executesql to run this dynamic query. The code will look something like this:

declare @colname varchar(50) = ''

declare @query nvarchar(8000) = 'INSERT INTO @temp (ranking,item,groupCount,groupName)'
+ 'SELECT RANK() OVER(ORDER BY COUNT(*) desc,' + @colname + ') [Rank],' + @colname 
+ 'COUNT(*) AS groupCount, 'currentMonth' AS groupName FROM Log_PE'
+ 'WHERE CONVERT(DATE, dateEsc, 120) >= CONVERT(DATE, CONVERT(VARCHAR(6), GETDATE(),112)      
+  '01', 112)'
+ 'GROUP BY ' + @colname
+ ' ORDER BY groupCount desc, ' + @colname

execute sp_executesql @query
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top