I am trying to write a stored procedure which selects columns from a table and adds 2 extra columns to the ResultSet. These 2 extra columns are the result of conversions on a field in the table which is a Datetime field.
The Datetime format field has the following format 'YYYY-MM-DD HH:MM:SS.S'
The 2 additional fields which should be in the following format:
- DDMMM
- HHMMT, where T is 'A' for a.m. and 'P' for p.m.
Example: If the data in the field was '2008-10-12 13:19:12.0' then the extracted fields should contain:
- 12OCT
- 0119P
I have tried using CONVERT string formats, but none of the formats match the output I want to get. I am thinking along the lines of extracting the field data via CONVERT and then using REPLACE, but I surely need some help here, as I am no sure.
Could anyone well versed in stored procedures help me out here? Thanks!
in MS SQL Server you can do:
SET DATEFORMAT ymd
year, month, day,
I'm adding this answer (for myself) as relevant to custom formatting.
For underscore yyyy_MM_dd
Not answering your question specifically, but isn't that something that should be handled by the presentation layer of your application. Doing it the way you describe creates extra processing on the database end as well as adding extra network traffic (assuming the database exists on a different machine than the application), for something that could be easily computed on the application side, with more rich date processing libraries, as well as being more language agnostic, especially in the case of your first example which contains the abbreviated month name. Anyway the answers others give you should point you in the right direction if you still decide to go this route.
You're going to need DATEPART here. You can concatenate the results of the DATEPART calls together.
To get the month abbreviations, you might be able to use DATENAME; if that doesn't work for you, you can use a CASE statement on the DATEPART.
DATEPART also works for the time field.
I can think of a couple of ways of getting the AM/PM indicator, including comparing new dates built via DATEPART or calculating the total seconds elapsed in the day and comparing that to known AM/PM thresholds.
Use DATENAME and wrap the logic in a Function, not a Stored Proc
Returns "14OCT"
Try not to use any Character / String based operations if possible when working with dates. They are numerical (a float) and performance will suffer from those data type conversions.
Dig these handy conversions I have compiled over the years...
Yes Depart is a solution for that but I think this kind of methods are long trips!
SQL SERVER:
Oracle:
You may write your own function by this way you can get rid of this mess;
http://sql.dzone.com/news/custom-date-formatting-sql-ser