Abhilash J A

Abhilash J A

  • 530
  • 2.4k
  • 600.5k

How can I use order by in dynamic query?

Oct 18 2016 5:06 AM
Hello everyone,
From this below query, Order by can not working when I am passing parameter @SortColumn. But it working directly passing value. For eg, if I am giving AgencyName asc instead of @SortColumn. Its working fine. How to solve this issue when I am passing parameter?
  1. DECLARE @StartRowNum varchar(10)  
  2. DECLARE @EndRowNum varchar(10)  
  3. DECLARE @SortColumn varchar(100)   
  4. DECLARE @TransId varchar(100)   
  5.   
  6. SET @SortColumn = 'AgencyName asc'  
  7. SET @TransId = 1481143433  
  8. SET @EndRowNum = 50  
  9. SET @StartRowNum = 0  
  10.   
  11. begin  
  12.   
  13. select  ROW_NUMBER() over (order by @SortColumn )  AS RowNum, tempID,ProgramId,ChannelId,Date_DL,StartTime,EndTime,Viewers,            
  14.   Tx,TVR,CVR,DVR,            
  15.   Details_Id,            
  16.    MastersId,BrandsId,ItemsId,Note,PaidForOrProp,Verbal,Indexes,Seconds,            
  17.      GradesId,ChannelName,CountryName,WebSiteName,ProductionName,BrandName,ItemName,            
  18.      Product_company_id,CompanyName,ProductGroupsId,            
  19.      SectorsId,SubSectoresId,AgenciesId,GroupName,SectorName,SubsectoreName,             
  20.      AgencyName,agencyID,QualityGrade,CPH_DL,CPH_UN,Country_CPH,Country_UN,            
  21.      Web_CPH,Web_UN,            
  22.  AdFactor,Duration_Factor,DaypartName,DaypartId,DaypartFactor,CinemaFactor,DigitalFactor,MediaValue from             
  23.  dbo.MonitorExposureFinal WHERE Trans_Id = @TransId   
  24.  end  

Answers (1)