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!
If dt is your datetime column, then
For 1:
For 2:
You can use the following command in SQL server to make it:
If it's something more specific like
DateKey
(yyyymmdd
) that you need for dimensional models, I suggest something without any casts/converts:That statement is false. That's just how Enterprise Manager or SQL Server chooses to show the date. Internally it's a 8-byte binary value, which is why some of the functions posted by Andrew will work so well.
Kibbee makes a valid point as well, and in a perfect world I would agree with him. However, sometimes you want to bind query results directly to display control or widgets and there's really not a chance to do any formatting. And sometimes the presentation layer lives on a web server that's even busier than the database. With those in mind, it's not necessarily a bad thing to know how to do this in SQL.