重写TSQL以消除游标

时间:2015-03-24 18:39:24

标签: tsql

有没有消除这个光标逻辑?

我需要迭代@YearMonth(最终看起来类似于:“2015-01”,“2015-02”,“201503”(截至当前日期)

DECLARE myCursor CURSOR
FOR SELECT DISTINCT(YearMonth) FROM Submissions
OPEN myCursor

FETCH NEXT FROM myCursor INTO @YearMonth
LOOP BEGIN
            INSERT INTO #EngagementCount (YearMonth, EngagmentCount)
            SELECT @YearMonth AS YearMonth COUNT(e.EngagementID) AS EngagementCount
            FROM Engagements AS e
            WHERE @YearMonth >= e.StartDate and @YearMonth < e.ExpiresOn
LOOP END

1 个答案:

答案 0 :(得分:0)

这应该有效:

SELECT YearMonth, COUNT(e.EngagementID) AS EngagementCount 
FROM Submissions s
INNER JOIN Engagements e ON s.YearMonth BETWEEN e.StartDate AND e.Expires
GROUP BY YearMonth