Solved

SQL: Order By case statement error message

Posted on 2014-10-09
6
256 Views
Last Modified: 2014-10-10
Error:  Conversion failed when converting date and/or time from character string.

When I run the stored procedure I get the above error ONLY WHEN @pSortBy = 'Customer Name'.

I have a stored procedure which needs to order by @pSortBy passed to the stored procedure.
If @pSortBy = 'Customer Name', then order by CA.Name1 which is a VARCHAR
If @pSortBy = 'Account Number' then order by CA.AccountNumber which is an INT
If @pSortBy = 'Projected Funding Date' then order by the calculated field below which is a DATETIME

CREATE PROCEDURE [pReport_ProjectedFunding]                        
@pTodayDate Datetime,
@pPayeeTypeId INT,
@pSpecificPayee VARCHAR(8000),                        
@pDisbursementDay INT,    
@pSortBy VARCHAR(50)                   
  
AS                        
BEGIN

SELECT *
FROM ...
WHERE ...


ORDER BY   
 (CASE @SortBy  
  WHEN 'Customer Name' THEN CA.[Name1]
  WHEN 'Account Number' THEN CA.AccountNumber 
  WHEN 'Projected Funding Date'   
   THEN (CASE WHEN CFD.Data IS NOT NULL   
       THEN (CASE WHEN dbo.GetWeekDay(CFD.Data) = DATEPART(dw, #tmpAnticipatedReleaseDate.AnticipatedReleaseDate)  
            THEN #tmpAnticipatedReleaseDate.AnticipatedReleaseDate  
            ELSE DATEADD(dd,   
            (CASE DATEPART(dw, #tmpAnticipatedReleaseDate.AnticipatedReleaseDate) - dbo.GetWeekDay(CFD.Data)  
             WHEN -3 THEN 3  
             WHEN -2 THEN 2  
             WHEN -1 THEN 1  
             WHEN  1 THEN 6  
             WHEN  2 THEN 5  
             WHEN  3 THEN 4  
            END)  
            , #tmpAnticipatedReleaseDate.AnticipatedReleaseDate)  
          END)     
       ELSE #tmpAnticipatedReleaseDate.AnticipatedReleaseDate  
      END)  
  ELSE CA.AccountNumber    
 END) 
 
 END

Open in new window

0
Comment
Question by:pzozulka
  • 2
  • 2
  • 2
6 Comments
 
LVL 48

Expert Comment

by:PortletPaul
Comment Utility
If you are ONLY getting that error for @pSortBy = 'Customer Name'

then the code snippet you have given us does not reveal the problem.
0
 
LVL 8

Author Comment

by:pzozulka
Comment Utility
Another developer here suggested to cast all fields after the THEN clause as varchar. This fixed the problem with the error message, however, the order by stopped working correctly as it wasn't sorting the date field correctly. They said something about the order by clause expecting a results of the case statemt to be a single data type.
0
 
LVL 48

Accepted Solution

by:
PortletPaul earned 500 total points
Comment Utility
>>"expecting ... case statemt to be a single data type"
expect it is a case expression, but that may be it.

maybe this will work?

ORDER BY
      CASE WHEN 'Customer Name' THEN CA.[Name1] ELSE NULL,
      CASE WHEN 'Account Number' THEN CA.AccountNumber  ELSE NULL,
      CASE WHEN 'Projected Funding Date'   ........  ELSE NULL,
      CA.AccountNumber
0
How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

 
LVL 69

Expert Comment

by:ScottPletcher
Comment Utility
You have to convert the int and datetime values to varchar values that will sort properly:

ORDER BY
 CASE @SortBy  
  WHEN 'Customer Name' THEN CA.[Name1]
  WHEN 'Account Number' THEN RIGHT(REPLICATE('0', 10) + CAST(CA.AccountNumber AS varchar(10)), 10)
  WHEN 'Projected Funding Date'  
   THEN CONVERT(varchar(8), (CASE WHEN CFD.Data IS NOT NULL  
       THEN (CASE WHEN dbo.GetWeekDay(CFD.Data) = DATEPART(dw, #tmpAnticipatedReleaseDate.AnticipatedReleaseDate)  
            THEN #tmpAnticipatedReleaseDate.AnticipatedReleaseDate
            ELSE DATEADD(dd,  
            (CASE DATEPART(dw, #tmpAnticipatedReleaseDate.AnticipatedReleaseDate) - dbo.GetWeekDay(CFD.Data)  
             WHEN -3 THEN 3  
             WHEN -2 THEN 2  
             WHEN -1 THEN 1  
             WHEN  1 THEN 6  
             WHEN  2 THEN 5  
             WHEN  3 THEN 4  
            END)  
            , #tmpAnticipatedReleaseDate.AnticipatedReleaseDate)  
          END)    
       ELSE #tmpAnticipatedReleaseDate.AnticipatedReleaseDate  
      END), 112)
  ELSE CA.AccountNumber    
 END
0
 
LVL 8

Author Comment

by:pzozulka
Comment Utility
Scott, as mentioned, we tried this and for some reason it is not sorting the calculated datetime correctly.

PortletPaul: Your solution worked great. Thanks.
0
 
LVL 69

Expert Comment

by:ScottPletcher
Comment Utility
>> Scott, as mentioned, we tried this and for some reason it is not sorting the calculated datetime correctly. <<

That's because you didn't format it correctly for sorting.  The format I used, YYYYMMDD, will sort correctly.  If you need to include the time, we could of done that as well.
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

How to leverage one TLS certificate to encrypt Microsoft SQL traffic and Remote Desktop Services, versus creating multiple tickets for the same server.
Use this article to create a batch file to backup a Microsoft SQL Server database to a Windows folder.  The folder can be on the local hard drive or on a network share.  This batch file will query the SQL server to get the current date & time and wi…
Using examples as well as descriptions, and references to Books Online, show the different Recovery Models available in SQL Server and explain, as well as show how full, differential and transaction log backups are performed
Viewers will learn how to use the UPDATE and DELETE statements to change or remove existing data from their tables. Make a table: Update a specific column given a specific row using the UPDATE statement: Remove a set of values using the DELETE s…

744 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

8 Experts available now in Live!

Get 1:1 Help Now