How to create temp table from a dynamic query?

元气小坏坏 提交于 2019-12-06 16:57:15

问题


I want to create dynamic query for paging [Main Motive], here is my code:

Alter proc proc_GetData
(
    @TableName varchar(500)='tblPropertyType',
    @PrimaryKey varchar(500)='Id',
    @Columns varchar(max)='PropertyType',
    @WhereCondition varchar(max)='',
    @RecsPerPage int =3,
    @Page int=1,
    @SortColumn varchar(500)='Id',
    @SortDirection Varchar(56)='asc'
)
as
DECLARE @SQL VARCHAR(MAX)
DECLARE @DSQL VARCHAR(MAX)
DECLARE @FirstRec int, @LastRec int
SET @FirstRec = (@Page - 1) * @RecsPerPage
SET @LastRec = (@Page * @RecsPerPage + 1)
select @FirstRec
select @LastRec
SET @SQL='
SELECT
ROW_NUMBER() OVER (ORDER BY ' + @SortColumn+ ' '+ @SortDirection +') RowNum,'+ @PrimaryKey +' , ' +@Columns + ' from ' +@TableName+ ' Where  1=1 '+
@WhereCondition

What I want to do is:

  • First: inert all the records in a temp table from the above query.
  • Second: SELECT * FROM @TEMPResult WHERE RowNum > @FirstRec AND RowNum < @LastRec.

Please help me


回答1:


SET @SQL='SELECT ROW_NUMBER() OVER 
   (ORDER BY ' + @SortColumn+ ' ' + @SortDirection + ') RowNum, ' + @PrimaryKey + ', ' + @Columns + ' 
   INTO tempTableName
   FROM ' + @TableName + ' Where  1 = 1 ' + @WhereCondition


来源:https://stackoverflow.com/questions/15614023/how-to-create-temp-table-from-a-dynamic-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!