问题
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