473,881 Members | 1,653 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Order By Case Cast Convert Error

I have created a SQL Stored Procedure that uses a Case statement to
determine the Order By. For one of the Case statements I am trying to
turn a Char field into Datetime in for the Order By, however I can not
get it to work. Can someone please take a look and my code below and
tell me what I am doing wrong. Thank you.

ORDER BY
CASE WHEN @SortBy = 'dttm_stamp' THEN dttm_stamp End,
CASE WHEN @SortBy = 'Event_Date1' THEN CAST(CONVERT(ch ar(10),
Event_Date1,101 ) as datetime) End,
CASE WHEN @SortBy = 'FullName' THEN Emp_lastname + ', ' +
Emp_firstname End,
CASE WHEN @SortBy = 'FullName Desc' THEN Emp_lastname + ', ' +
Emp_firstname End DESC,
CASE WHEN @SortBy = 'Emp_SSN' THEN Emp_SSN End

Jul 23 '05 #1
11 3823

<jg*******@cybe rgroup.com> wrote in message
news:11******** *************@c 13g2000cwb.goog legroups.com...
I have created a SQL Stored Procedure that uses a Case statement to
determine the Order By. For one of the Case statements I am trying to
turn a Char field into Datetime in for the Order By, however I can not
get it to work. Can someone please take a look and my code below and
tell me what I am doing wrong. Thank you.

ORDER BY
CASE WHEN @SortBy = 'dttm_stamp' THEN dttm_stamp End,
CASE WHEN @SortBy = 'Event_Date1' THEN CAST(CONVERT(ch ar(10),
Event_Date1,101 ) as datetime) End,
CASE WHEN @SortBy = 'FullName' THEN Emp_lastname + ', ' +
Emp_firstname End,
CASE WHEN @SortBy = 'FullName Desc' THEN Emp_lastname + ', ' +
Emp_firstname End DESC,
CASE WHEN @SortBy = 'Emp_SSN' THEN Emp_SSN End


What does "can not get it to work" mean? Do you get errors, or do you get
unexpected results? The best idea would probably be to post CREATE TABLE and
INSERT statements to set up a test case which illustrates your problem.

http://www.aspfaq.com/etiquette.asp?id=5006

Simon
Jul 23 '05 #2
On 17 Jan 2005 09:42:05 -0800, jg*******@cyber group.com wrote:
I have created a SQL Stored Procedure that uses a Case statement to
determine the Order By. For one of the Case statements I am trying to
turn a Char field into Datetime in for the Order By, however I can not
get it to work. Can someone please take a look and my code below and
tell me what I am doing wrong. Thank you.
Hi jquilford,

I guess that this is the line that's giving you trouble:
CASE WHEN @SortBy = 'Event_Date1' THEN CAST(CONVERT(ch ar(10),
Event_Date1,10 1) as datetime) End,


You are converting the datetime variable to the american mm/dd/yyyy
format, which is not very well suited for sorting. Then you are converting
it back to datetime, running alll kinds of risks because this format is
ambiguous - it's easily misinterpreted as dd/mm/yyyy, causing either wrong
sorting or conversion errors.

If your intention is to strip the time part from the datetime column, so
you can order by the date part only, use

CASE WHEN @SortBy = 'Event_Date1' THEN DATEADD(day, DATEDIFF(day,
'20000101', Event_Date1), '20000101')

Or, if you really want to do it by conversion to string and back, use the
safe yyyymmdd format:

CASE WHEN @SortBy = 'Event_Date1' THEN CAST(CONVERT(ch ar(8),
Event_Date1,112 ) as datetime) End,

Best, Hugo
--

(Remove _NO_ and _SPAM_ to get my e-mail address)
Jul 23 '05 #3
Hugo Kornelis (hugo@pe_NO_rFa ct.in_SPAM_fo) writes:
Or, if you really want to do it by conversion to string and back, use the
safe yyyymmdd format:

CASE WHEN @SortBy = 'Event_Date1' THEN CAST(CONVERT(ch ar(8),
Event_Date1,112 ) as datetime) End,


Or simply say:

CASE WHEN @SortBy = 'Event_Date1'
THEN CONVERT(char(8) , Event_Date1,112 )
End,

Then again, we have no idea jguildford mean "I can not get it to work".

--
Erland Sommarskog, SQL Server MVP, es****@sommarsk og.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techinf...2000/books.asp
Jul 23 '05 #4
On Mon, 17 Jan 2005 22:40:11 +0000 (UTC), Erland Sommarskog wrote:
Hugo Kornelis (hugo@pe_NO_rFa ct.in_SPAM_fo) writes:
Or, if you really want to do it by conversion to string and back, use the
safe yyyymmdd format:

CASE WHEN @SortBy = 'Event_Date1' THEN CAST(CONVERT(ch ar(8),
Event_Date1,112 ) as datetime) End,
Or simply say:

CASE WHEN @SortBy = 'Event_Date1'
THEN CONVERT(char(8) , Event_Date1,112 )
End,


Hi Erland,

Of course - no need to change it back to datetime in this case. Thanks!

Then again, we have no idea jguildford mean "I can not get it to work".


Maybe he (she?) will post with more details?

Best, Hugo
--

(Remove _NO_ and _SPAM_ to get my e-mail address)
Jul 23 '05 #5
1) why are you using a CASE expression in an ORDER BY? Is the
destruction of portable code one of your design goals?

2) The column used for a sort should appear in the output so a human
being can use it to search the list. Basic human factors, etc. Put it
in the SELECT list.

3) Why are you making a date into a string in the first place? You can
sort of temporal datatypes too. And why are you converting it to a
string that is not in temporal order?

Jul 23 '05 #6
Let me try to better explain my problem. I have created a page in
asp.net that has a datagrid that pulls a few fields form a SQL Server
table. Also on this page there is a dropdown box that allows you to
pick the way the data is sorted. You can pick to sort it by the data
the record was created, name (both ascending and descending), social
security number and by the date of the event. Now here is my problem,
the Event_Date1 field is a 10 character field (00/00/0000) instead of a
datetime field, it was set up like this a long time ago and can not be
changed. Because it is a character field when you use it to sort the
data it is sorted by month then day then year instead of year then
month then day. I tried to use a Cast and Convert statement to change
it to a datetime so it would sort correctly but now when I try to sort
by Event_Date1 I receive this error: "The conversion of a char data
type to a datetime data type resulted in an out-of-range datetime
value." I have included all of the code in my stored procedure below.
I hop this clears up some of the confusion. Let me know if there is
anything else I did not clear up. Thank you.

CREATE PROCEDURE spShowArchives
@SecurityID int,
@SortBy varchar(50)
AS
SELECT ID, Emp_lastname + ', ' + Emp_firstname as FullName, Emp_SSN,
Event_Date1, Injury_Illness_ Type, Jurisdiction, Injury_Cause_De sc,
SISCO_claim, dttm_stamp FROM omni_table
WHERE security_id = @SecurityID
AND omni_table.dele ted_flag = 0
AND (SISCO_claim <> '' or SISCO_claim <> null or SISCO_claim <>
'Submit')
ORDER BY
CASE WHEN @SortBy = 'dttm_stamp' THEN dttm_stamp End,
CASE WHEN @SortBy = 'Event_Date1' THEN CAST(CONVERT(ch ar(10),
Event_Date1,101 ) as datetime) End,
CASE WHEN @SortBy = 'FullName' THEN Emp_lastname + ', ' +
Emp_firstname End,
CASE WHEN @SortBy = 'FullName Desc' THEN Emp_lastname + ', ' +
Emp_firstname End DESC,
CASE WHEN @SortBy = 'Emp_SSN' THEN Emp_SSN End
GO

Jul 23 '05 #7
On 18 Jan 2005 11:53:03 -0800, jagguil4d wrote:
Let me try to better explain my problem. (snip) Now here is my problem,
the Event_Date1 field is a 10 character field (00/00/0000) instead of a
datetime field, it was set up like this a long time ago and can not be
changed.
Hi jagguil4d / jguilford,

This is not correct. Of course it *can* be changed. You probably meant to
write that someone in your organization doesn't *want* it to be changed.
And that someone is most likely the person who's budget is impacted by the
cost of actually imprivong your system, but doesn't suffer from the
(eventually) much higher costs of numerous workarounds, bugfixes and error
recovery.

Because it is a character field when you use it to sort the
data it is sorted by month then day then year instead of year then
month then day. I tried to use a Cast and Convert statement to change
it to a datetime so it would sort correctly but now when I try to sort
by Event_Date1 I receive this error: "The conversion of a char data
type to a datetime data type resulted in an out-of-range datetime
value."


You might try if you have more luck with
CASE WHEN @SortBy = 'Event_Date1' THEN CONVERT(datetim e, Event_Date1,
101) End,

If that fails as well, you have at least one row in your table with an
invalid date (and boy, are you lucky if it is indeed only one <g>). These
can be hard to find. A good starting point would be
SELECT KeyColumn, Event_Date1
FROM omni_table
WHERE ISDATE(Event_Da te1) = 0

If the above returns no rows, but you get errors converting Event_Date1 to
datetime, then you probably have rows with a date in DD/MM/YYYY format, or
some other date format. The following will hopefully catch most of these
buggers:
SELECT KeyColumn, Event_Date1
FROM omni_table
WHERE Event_Date1 >= '13'
OR Event_Date1 NOT LIKE '[0-9][0-9]/[0-9][0-9]/[0-9][0-9][0-9][0-9]'

Good luck! (You'll need it...)

Best, Hugo
--

(Remove _NO_ and _SPAM_ to get my e-mail address)
Jul 23 '05 #8
jagguil4d (jg*******@cybe rgroup.com) writes:
Now here is my problem, the Event_Date1 field is a 10 character field
(00/00/0000) instead of a datetime field, it was set up like this a long
time ago and can not be changed.


Of course it can! I hear this lame excuse every time, but seriously,
yes it can be changed. Just why would it be left unchanged?

Anyway, as Hugo points out you have garabge in this column, so if
you insist on that you don't want to change it, do this:

CASE WHEN @SortBy = 'Event_Date1' THEN
substring(Event _Date1, 7, 4) + substring(Event _Date1, 1, 2) +
substring(Event _Date1, 4, 2)
--
Erland Sommarskog, SQL Server MVP, es****@sommarsk og.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techinf...2000/books.asp
Jul 23 '05 #9
--CELKO-- (jc*******@eart hlink.net) writes:
1) why are you using a CASE expression in an ORDER BY? Is the
destruction of portable code one of your design goals?


Because he more cares about serving his users than paying sacrifice
to the Holy Church of Portability.
--
Erland Sommarskog, SQL Server MVP, es****@sommarsk og.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techinf...2000/books.asp
Jul 23 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
3677
by: svilen | last post by:
hello again. i'm now into using python instead of another language(s) for describing structures of data, including names, structure, type-checks, conversions, value-validations, metadata etc. And i have things to offer, and to request. And a lot of ideas, but who needs them.... here's an example (from type_struct.py):
1
4922
by: Hifni Shahzard | last post by:
Hi, I got a stored procedure, where it returns a value. But if I execute it. It gives an error as "Invalid cast from System.Int32 to System.Byte.". To make clear how do I execute this, below I'm specifiying my code: The Code used in Visual Studio: Function GetRank(ByVal ID As Integer, ByVal Comp As String, ByVal Sec As String, ByVal iDate As Date) As String 'Dim Ret As Integer
7
6343
by: Giles | last post by:
An ASP page outputs data from the query "Select ThisAndThat from comments WHERE pageURL='" & pageURL & "' ORDER BY threadID, datesent" (Access mdb) threadID is a string (OK, I know!), which means that 103 displays before 99. Is there a way to write the SQL query to order them numerically? This would be much easier for me than changing the data type and hunting down every page that INSERTS or UPDATES the db. Thanks, Giles
29
27628
by: pb648174 | last post by:
I have the following basic statements being executed: Create a temp table, #TempPaging Insert Into #TempPaging (Col1, Col2) Select Col1, Col2 From SomeOtherTable Order By Col2, Col1 Select * from #TempPaging I can't provide a reproduceable scenario right now without making this
7
6354
by: mandible | last post by:
Hello I'm trying to have some control on how my data is ordered depending on an input parameter my question is in a stored procedure how can I do something like this at the end of my statement. pOrder as input value where pOrder can be 1 or 0
1
8445
by: Pacific Fox | last post by:
Hi all, I have a SQL statement that allows paging and dynamic sorting of the columns, but what I can't figure out without making the SQL a dynamic string and executing it, or duplicating the SQL statement between an IF and ELSE statement. Following is the SQL statement; set ANSI_NULLS ON
4
4313
by: Pacific Fox | last post by:
I am using a dynamic order by statement; ORDER BY CASE @sort WHEN 0 THEN CAST( COALESCE( t2.RANK, 0 ) + COALESCE( t3.RANK, 0 ) AS CHAR( 5 ) ) WHEN 1 THEN C.title WHEN 2 THEN CAST( CEILING( . ( @fromLatitude, @fromLongitude, L.latitude, L.longitude ) ) AS CHAR( 9 ) ) WHEN 3 THEN ( C.locality + ' ' + C.state )
1
1977
by: santoshsri | last post by:
Hi below is a SQL Query written at SQL Server 2000. The result has been ordered by a.Location_Number , a.Transaction_Date, but in output the result is not ordered for eg : I am getting records for locaton no 1,2,3,10,12,13,14,2,2,2,2,3 .. but it should be like this 1,2,2,2,2,2,3,3,10,12,13,14.. Any Suggestion plz .. ? ******************************************************************************************* IF...
7
3954
by: * Tong * | last post by:
Hi, I couldn't figure out how to properly type cast in this case: $ cat -n type_cast.c 1 #include <stdio.h> 2 3 typedef unsigned char Byte; 4 typedef signed char Small_Int; 5
0
9776
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10718
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10816
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9554
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7953
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5977
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4597
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
4196
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3225
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.