There is some issue with you code:-
Just run the below code and you will get you required output.
DECLARE @TableName VARCHAR(50),
@ColName VARCHAR(50),
@OrderByClause VARCHAR(50),
@Code VARCHAR(MAX),
@StartIndex VARCHAR(50),
@EndIndex VARCHAR(50),
@QUERY VARCHAR(MAX)
SET @TableName = 'tblCountry'
SET @ColName = 'countryname'
SET @OrderByClause = 'desc'
SET @StartIndex = '2'
SET @EndIndex = '10'
SET @Code = 'With temp as (select row_number()
over (order by @ColName @OrderByClause) as row, * from @TableName)
select * from temp where row between @StartIndex and @EndIndex'
SET @QUERY = REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(@Code, '@TableName', @TableName)
, '@ColName', @ColName)
, '@OrderByClause', @OrderByClause)
, '@StartIndex', @StartIndex)
, '@EndIndex', @EndIndex)
EXECUTE (@QUERY)
Here if you want to select only required columns then see the below code:- DECLARE @TableName VARCHAR(50),
@ColName VARCHAR(50),
@OrderByClause VARCHAR(50),
@Code VARCHAR(MAX),
@StartIndex VARCHAR(50),
@EndIndex VARCHAR(50),
@QUERY VARCHAR(MAX),
@ColumnName VARCHAR(500)
SET @TableName = 'tblCountry'
SET @ColName = 'countryname'
SET @OrderByClause = 'desc'
SET @StartIndex = '2'
SET @EndIndex = '10'
SET @ColumnName = 'countryname'
SET @Code = 'With temp as (select row_number()
over (order by @ColName @OrderByClause) as row, * from @TableName)
select @ColumnName from temp where row between @StartIndex and @EndIndex'
SET @QUERY = REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@Code, '@TableName', @TableName), '@ColName', @ColName), '@OrderByClause', @OrderByClause), '@StartIndex', @StartIndex), '@EndIndex', @EndIndex), '@ColumnName', @ColumnName)
EXECUTE (@QUERY)
If this helps you towards the solution, click on
MARK IT AS ANSWER Happy Coding.
Sharpcnet, if this helps please login to Mark As Answer. | Alert Moderator