Friday, 2 August 2013

Common Table Expressions(CTE) in SQL SERVER



Common Table Expressions(CTE) in SQL SERVER 



/* SP_GET_RECENTLY_ANSWERED_QUESTION 50  */
IF EXISTS(select * from sysobjects where name='SP_GET_RECENTLY_ANSWERED_QUESTION' and xtype='p')
BEGIN
DROP PROCEDURE SP_GET_RECENTLY_ANSWERED_QUESTION
END
GO
CREATE PROCEDURE [dbo].[SP_GET_RECENTLY_ANSWERED_QUESTION]
@MaxResults int
AS
BEGIN
WITH RecentlyAnswered(QuestionId,ActionDate) AS

SELECT TOP 10000 QuestionId,ActionDate 
FROM QuestionDetail ORDER BY 2 desc
)

SELECT Q.QuestionId, Q.DETAIL,Q.ASKEDDATE,Q.AskedBy ,U.FIRSTNAME, U.USERID FROM QUESTION Q
LEFT JOIN [USER] U
ON Q.ASKEDBY=U.USERID 
WHERE Q.QuestionId IN (SELECT DISTINCT TOP (@MaxResults) QuestionId FROM RecentlyAnswered)
ORDER BY Q.ASKEDDATE DESC

END

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home