在SQL中的公用表表达式中执行语句

时间:2014-09-03 13:25:43

标签: sql-server-2008 common-table-expression

当我试图在公共表表达式中使用执行语句时,我收到错误。我已经给出了下面的代码。请帮我解决这个问题。

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 

1 个答案:

答案 0 :(得分: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 '+@StartIndex+' and '+  @EndIndex+' 
')
END