如何在SQL Server中的CTE内执行字符串作为查询

时间:2014-04-14 07:58:02

标签: sql sql-server

我正在使用下面的CTE ...但是我收到了像

这样的错误
  

没有为'TempResult'的第1列指定列名。

此外,我从另一个存储过程传递@Query,在此过程中,我需要在CTE @Query内执行TempResult

CREATE PROCEDURE [dbo].[SelectAllProjectPaging]      
    @CurrentPage int,                          
    @RecordsPerPage int,  
    @Column varchar(50),  
    @Query nvarchar(max)   
AS      
BEGIN      
    -- SET NOCOUNT ON added to prevent extra result sets from      
    -- interfering with SELECT statements.      
    SET NOCOUNT ON;      

    DECLARE @query nvarchar(max)
    SET @query = 'ROW_NUMBER() OVER(ORDER BY ProjectList.ProjectId DESC) as RowNumber,' + @Query

    -- Insert statements for procedure here      
    DECLARE @FirstRecord int, @LastRecord int                       

    SELECT @FirstRecord = (@CurrentPage - 1) * @RecordsPerPage              
    SELECT @LastRecord = (@CurrentPage * @RecordsPerPage + 1);              

    WITH TempResult as              
    (                                
         Select @query
    )            
    SELECT TOP (@LastRecord - 1) *  
    FROM TempResult              
    WHERE RowNumber > @FirstRecord 
      AND RowNumber < @LastRecord;              

    SELECT COUNT(*) as count 
    FROM ProjectList          
 End

2 个答案:

答案 0 :(得分:5)

您需要使用动态sql进行整个查询。像这样的东西:

SET @query= 'WITH TempResult as              
             (                                
                SELECT + ' + @query + 
            ')            
             SELECT TOP (' + CAST((@LastRecord - 1) AS VARCHAR(20)) +
            ') * FROM TempResult              
             WHERE RowNumber > ' + CAST(@FirstRecord AS VARCHAR(20)) +
           ' AND RowNumber < ' + CAST(@LastRecord AS VARCHAR(20)) + '; '

EXECUTE @query

修改

评论。是的它应该选择我能看到的东西。 @query等于:

set @query = 'ROW_NUMBER() OVER(ORDER BY ProjectList.ProjectId DESC) as RowNumber,'+ @query

然后你需要:

SELECT ' ROW_NUMBER() OVER(ORDER BY ProjectList.ProjectId DESC) as RowNumber,' + @query

答案 1 :(得分:-1)

你的&#34;与TempResult As&#34;必须扩展一点,包含要使用的列名。

示例

With TempResult (column1, column2, column3) as 
(
    select @query
)

价:

WITH expression_name [ ( column_name [,...n] ) ]
AS
    ( CTE_query_definition )

来自http://technet.microsoft.com/en-us/library/ms190766%28v=sql.105%29.aspx