CREATE TABLE TempTable
(
Sno INT IDENTITY(1,1),
UserId INT,
DeptId INT,
FirstName varchar(100),
Lastname varchar(100),
Email varchar(100),
IsDeleted bit
)
INSERT INTO TempTable VALUES(1,2,'John','Smith','jsmith@gamil.com',0)
INSERT INTO TempTable VALUES(1,2,'Tom','Cruse','tcruse@gamil.com',0)
INSERT INTO TempTable VALUES(1,2,'Sunny','Leone','sl@yahoo.com',0)
INSERT INTO TempTable VALUES(1,2,'Kat','Wins','kat@hotmail.com',0)
INSERT INTO TempTable VALUES(1,2,'Amit','Kappa','akappa@gamil.com',0)
DECLARE @SQLQuery NVARCHAR(2000)
DECLARE @TableName AS NVARCHAR(200)
DECLARE @NthColumn AS INT
DECLARE @NthRow AS NVARCHAR(1000)
DECLARE @ColName AS VARCHAR(100)
SET @TableName ='TempTable'
SET @NthColumn=6
SET @NthRow = '5'
SELECT @ColName = COL_NAME(OBJECT_ID(@TableName),@NthColumn)
SET @SQLQuery = 'SELECT ' + @ColName + ' FROM ' + '(
SELECT *,ROW_NUMBER() OVER (ORDER BY ' + @ColName +' DESC) R FROM '+@TableName+ ' ) Temp
WHERE R='+ @NthRow
PRINT @SQLQuery
Exec(@SQLQuery)
DROP TABLE TempTable