Take this:DECLARE @pageNumber int = 1, @itemsPerPage int = 25,@totalRecords int, @sortByFieldName nvarchar(50) = 'TrackName', @columnName nvarchar(50) = NULL,@columnValue nvarchar(50) = NULL DECLARE @firstRow int DECLARE @lastRow int SELECT @firstRow = (@pageNumber - 1) * @itemsPerPage + 1, @lastRow = (@pageNumber - 1) * @itemsPerPage + @itemsPerPage, @totalRecords = (SELECT COUNT(p.[TrackID]) FROM Tracks p); WITH TracksSummary AS ( SELECT p.TrackID, p.ArtistID, p.GenreID, p.TrackName, p.FullDuration, ROW_NUMBER() OVER (ORDER BY CASE @sortByFieldName WHEN 'ID' THEN CAST(TrackID as nvarchar(50)) WHEN 'TrackName' THEN TrackName WHEN 'Duration' THEN CAST(FullDuration as nvarchar(50)) WHEN 'aid' THEN CAST(ArtistID as nvarchar(50)) END ASC) AS RowNumber FROM Tracks p ) SELECT RowNumber, TrackID, ArtistID, GenreID, TrackName, FullDuration FROM TracksSummary WHERE RowNumber BETWEEN @firstRow AND @lastRow ORDER BY CASE @sortByFieldName WHEN 'ID' THEN CAST(TrackID as nvarchar(50)) WHEN 'TrackName' THEN TrackName WHEN 'Duration' THEN CAST(FullDuration as nvarchar(50)) WHEN 'aid' THEN CAST(ArtistID as nvarchar(50)) END
Now, this works nicely in terms of ordering it by TrackName and anything "string" related.But when I give it the ID - the ordering does not happen in the usual way an int column would be ordered by but instead by the string rules.I understand this is because I am doing a cast from int to nvarchar but this seems to be the only solution that works when trying to do a non dynamic T-SQL.is there a workaround for this or a way to do a correct order by when it involves a column which is of an int value?please provide a reasonable explanation with code samples where possible.thank you!