In my last project I wrote a query where I have to sort data based on the user input but each column in table has different data type. So to meet with this type of requirement I have used case..when block of the sql server. 
Problem: Sample query
DECLARE @sortby Varchar(10)
Set @sortby = 'A1'
Select String1,String2,DateCol
from (
select 'A1','B1', GetDateTime() 
union
select 'A2','B2', GetDateTime()
)  As d(String1,String2,DateCol)
Order by
Case
When @sortby = 'A1' then String2
When @sortby = 'B1' then String1
When @sortby = 'Date' then Date1 
End
there is not syntax error when you check for the syntax error but when execute code you find there is error 
ERROR:Conversion failed when converting datetime from character string.
the problem here is first two having databype Varchar and last one having datatype DateTime. So when you executing its found that one branch having datetime so its gives error even its not executing that.
Solution
First Solution 
So to avoid this problem you require to convert dateTime to the string
DECLARE @sortby Varchar(10)
Set @sortby = 'A1'
Select String1,String2,DateCol
from (
select 'A1','B1', GetDateTime() 
union
select 'A2','B2', GetDateTime()
)  As d(String1,String2,DateCol)
Order by
Case
When @sortby = 'A1' then String2
When @sortby = 'B1' then String1
When @sortby = 'Date' then Cast(Date1  as varchar(20))
End
Second Solution
Divide the Case when in multiple statement
DECLARE @sortby Varchar(10)
Set @sortby = 'A1'
Select String1,String2,DateCol
from (
select 'A1','B1', GetDateTime() 
union
select 'A2','B2', GetDateTime()
)  As d(String1,String2,DateCol)
Order by
Case When @sortby = 'A1' then String2 End,
Case When @sortby = 'B1' then String1 End,
Case When @sortby = 'Date' then Date1  End
Sharing real-world experiences about C#, Dynamics CRM, Dynamics 365, Dynamics NAV/Business Central, SharePoint,PowerBI,ASP.net and more...
Subscribe to:
Post Comments (Atom)
Method 'StartWorkflowOnListItem' in type 'Microsoft.SharePoint.WorkflowServices.FabricWorkflowInstanceProvider'
Exception: Method 'StartWorkflowOnListItem' in type 'Microsoft.SharePoint.WorkflowServices.FabricWorkflowInstanceProvider'...
- 
Packt Publishing recently released a new book titled – Instant Razor View Engine authored by Abhimanyu Kumar Vatsa . I have also atta...
- 
Last day, I have got a mail from a junior developer he needs some help about custom attributes. He has no previous experience about it. I h...
- 
Basically, a thin client is a web based application and most of the processing is done on the server side. A thick client is installed int...
 
 
 
 
No comments:
Post a Comment