2014-09-03 61 views
0

當我嘗試在公用表表達式中使用execute語句時,出現錯誤。我已經給出了下面的代碼。請幫我解決問題。SQL中的公用表表達式執行語句

set @SQLStatement = 'select * from [Customers].[dbo].[Customer]'; 

with cte as 
(
exec (@SQLStatement) 
), 
cte1 as 
(
select ROW_NUMBER() OVER (ORDER BY (select null)) AS RowNumber,* from cte 
) 
select * from cte1 

Msg 156, Level 15, State 1, Procedure Get, Line 31 
Incorrect syntax near the keyword 'exec'. 
Msg 102, Level 15, State 1, Procedure Get, Line 33 
Incorrect syntax near ')'. 

這裏是我的SP

ALTER PROCEDURE [dbo].[Get] 
@StartIndex int, 
@EndIndex int, 
@SQLStatement varchar(max) 
AS 
BEGIN 



;with cte as 
(

exec (@SQLStatement) 

), 
cte1 as 
(
select ROW_NUMBER() OVER (ORDER BY (select null)) AS RowNumber,* from cte 
) 
select * from cte1 where RowNumber between @StartIndex and @EndIndex 

END 
+0

你不能做到這一點的CTE。一個cte是一個內聯視圖,不是任何你想要的容器。從你發佈的內容看,我沒有看到動態sql的任何需求。在你的真實情況下,你應該看看使用臨時表而不是cte。 – 2014-09-03 14:17:00

+0

你在哪裏得到了可以在CTE中使用動態sql的想法?因爲這不是真的可行,所以你應該解釋你整體想要做什麼,所以我們可以幫助那個 – Lamak 2014-09-03 14:17:14

+0

嗨,我正在研究一個存儲過程,它將從select中返回所需的行數語句,例如你的select語句返回了100萬行,我只需要從1到2000的行。我創建了以下sp,將select查詢作爲參數,startindex和endindex作爲其他參數都是動態的 – user1367984 2014-09-03 14:38:10

回答

0
ALTER PROCEDURE [dbo].[Get] 
@StartIndex int, 
@EndIndex int, 
@WhereStmt varchar(max) 
AS 
BEGIN 
execute(' 
;with cte as 
(
select * from customer '+ @WhereStmt+' 
), 
cte1 as 
(
select ROW_NUMBER() OVER (ORDER BY (select null)) AS RowNumber,* from cte 
) 
select * from cte1 where RowNumber between '[email protected]+' and '+ @EndIndex+' 
') 
END