Click here to Skip to main content
16,004,991 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
--scenario

SQL
ALTER PROCEDURE [dbo].[APPROVED_KM]-- 20,0,15,4
(
@HUB_ID INT,
@Pageindex int,
@pageSize int,
@totalrows int output
)
AS
BEGIN




C#
; with cte as
       (

--all the codes are written inside the cte which i am not showing here
     
       )




--first query after cte


SQL
select
      @totalrows=count(rownum)
from cte



--second query after cte

SQL
select
     *
from 
    cte
order by address_id
OFFSET ((@Pageindex+1)-1)*@pageSize ROWS
FETCH NEXT @pageSize ROWS ONLY



---now when i executed the stored procedure ...."invalid object cte"


----------------------------------to avoid the problem i tried this-----------------------

SQL
select *
into #temp1
from cte


select
      @totalrows=count(rownum)
from
      #temp1
 
         print @totalrows
 
 
 
select
     *
from 
     #temp1
order by address_id
OFFSET ((@Pageindex+1)-1)*@pageSize ROWS
FETCH NEXT @pageSize ROWS ONLY



--is there any way to do without inserting into temporary table...is it possible to do with cte itself [execute the two query]
Posted

1 solution

No, you can't use CTE outside the CTE. The only way is to use temporary table ;)
SQL
;WITH CTE AS
(
    --SELECT ...
)
INSERT INTO @tmp (DestField1, DestField2, ...)
SELECT (CteField1, CteField2, ...)
FROM CTE

SELECT @total = COUNT(*)
FROM @tmp

--and so on...
 
Share this answer
 
Comments
anurag19289 25-Sep-13 16:20pm    
ok coool :)
Maciej Los 25-Sep-13 16:32pm    
;)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900