Solved

SQL: Order By case statement error message

Posted on 2014-10-09
6
269 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
ID: 40372096
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
ID: 40372123
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
ID: 40372140
>>"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
Ransomware: The New Cyber Threat & How to Stop It

This infographic explains ransomware, type of malware that blocks access to your files or your systems and holds them hostage until a ransom is paid. It also examines the different types of ransomware and explains what you can do to thwart this sinister online threat.  

 
LVL 69

Expert Comment

by:Scott Pletcher
ID: 40373432
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
ID: 40373538
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:Scott Pletcher
ID: 40373545
>> 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

Backup Solution for AWS

Read about how CloudBerry Backup fully integrates your backups with Amazon S3 and Amazon Glacier to provide military-grade encryption and dramatically cut storage costs on any platform.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Table where row act as column 11 68
SQL Sum of items in two tables not equal. 5 43
Ideas on migrating very large  system from SQL 2005 to SQL 2014 3 28
Replication failure 1 19
In this article I will describe the Backup & Restore method as one possible migration process and I will add the extra tasks needed for an upgrade when and where is applied so it will cover all.
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
Via a live example, show how to backup a database, simulate a failure backup the tail of the database transaction log and perform the restore.
Via a live example, show how to setup several different housekeeping processes for a SQL Server.

713 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