Quantcast
Channel: SQLServerCentral » SQL Server 2014 » Development - SQL Server 2014 » Latest topics
Viewing all articles
Browse latest Browse all 3145

RowNumber issue

$
0
0
I have a query that worked perfectly fine until I added a Row_Number column in with a Date column specified in the order clause.The error I get is:Msg 241, Level 16, State 1, Line 27Conversion failed when converting date and/or time from character string.I assumed it was because I had both a date and varchar column in the case statement. But it only doesn't work if the @SortOrder is "DocumentName" (varchar). But if I have @SortOrder as "[Year]" (varchar) or "ExpirationDate" (DateTime), it works fine. Why would the first one cause a problem?[code]DECLARE @SortOrder VARCHAR(100), @SortDirection VARCHAR(100)SELECT @SortDirection = 'ASC'SELECT @SortOrder = 'DocumentName'--SELECT @SortOrder = '[Year]'--SELECT @SortDirection = 'ExpirationDate'DROP TABLE #TestCREATE TABLE #TEST( DocumentName VARCHAR(100), [Year] VARCHAR (4), ExpirationDate DateTime)INSERT #Test (DocumentName,[Year],ExpirationDate)VALUES ('Document 1', '2014', '02/01/2015')INSERT #Test (DocumentName,[Year],ExpirationDate)VALUES ('Document 2', '2011', '05/09/2013')INSERT #Test (DocumentName,[Year],ExpirationDate)VALUES ('Document 1', '2013', '11/01/2014')INSERT #Test (DocumentName,[Year],ExpirationDate)VALUES ('Document 1', '2012', '11/12/2012')SELECT DocumentName, [Year], ExpirationDate, ROW_NUMBER() OVER ( ORDER BY CASE WHEN @SortDirection = 'ASC' THEN CASE @SortOrder WHEN 'DocumentName' THEN DocumentName WHEN 'Year' THEN [Year] WHEN 'ExpirationDate' THEN ExpirationDate END END ASC)FROM #TEST[/code]Thanks,Tom

Viewing all articles
Browse latest Browse all 3145

Trending Articles