04
Dec
07

SQLserver date manipulation and formatting

MicroSoft SQLserver has some pretty slick features, but one area where they are definitely sucking is date manipulation and formatting. Joseph complained about this a while ago, but it’s time to me to chime in now.

My biggest complaint is the half-assed implementation of a reasonable design: Instead of having separate “date” and “time” datatypes, they provide a single “datetime” type. As far as I’m concerned that’s a good thing since it merges three separate types into one. But it’s an incomplete implementation because there isn’t a simple way to extract the date or time from a datatime type. There are functions to extract individual “fields” of the date or time, e.g. day of the month, hour of the day, etc. What I’d prefer would be a function(s) that would return only the date and/or time from a datetime agglomeration.

I’m currently trying to write a query that goes back to the beginning of the sixth month in the past, in order to implement a “recent orders” view. If I use the dateadd() and getdate() functions, I can get pretty close to my goal:

select dateadd( mm, -6,    -- Go back 6 months from...
            getdate() + 1 - day(getdate()))    -- 1st of this month
    ))

The problem with the code above is that it returns the correct date, but the time part will be set to whatever time this code was executed. If I run this query at 12:34 in the afternoon, I won’t see orders placed on the morning of the first day I wish to report. The easiest way I’ve found to get around this to use convert() twice: once to strip off the time (returning a varchar), and again to convert the varchar back into a datetime:

select convert(datetime,    -- Convert back to datetime
    convert(varchar(11),    -- Truncate off the time 
        dateadd( mm, -6,    -- Go back 6 months from...
            getdate() + 1 - day(getdate()))    -- 1st of this month
    ))

The default format for converting datetime to/from varchar is “Mon DD YYYY HH:MIAM”, so above I’m grabbing the first 11 characters (”Mon DD YYYY”) of the converted string and passing them right back to convert() and asking for a datetime. Since I haven’t supplied a time, it defaults to midnight.


0 Responses to “SQLserver date manipulation and formatting”


  1. No Comments

Leave a Reply




December 2007
M T W T F S S
« Nov   Jan »
 12
3456789
10111213141516
17181920212223
24252627282930
31  

Tags

abramoff accessibility acetylene activism aerial photo afrofunk aim4tree air america airport express alite alito amtrak andante andy anti failure any browser apache apple applescript arden arcade arden park ariana arnold ashland astronomy attic attika audio avid reader backup baen bart bathroom bbq bee beef begonia bgg bike bike hikers bike journal bikejournal biketalk bill oreilly bittorrent blacklist blog bloggercode blogroll blueberry boardgamegeek boardgames bonjour book bookcrossing boot failure bootcamp borderline chaos bugmenot bush business card cabinetry caira caitlin california candamir caroline carpet cat cateye cdrom celebration cellular phone century cheese chicken chico chimney chinese chipotle chocolate christmas chumby city bikes civilization cjd claire club club fed co op coconut coffee comfort food community computer concord congress conquest conservation consumer reports copyright costco crazybikerchick crepe crock pot cruftbox css csus curl currency custard cvntrak dagoba daniel goetz darwinports datarescue date format death delicious monster democracy now Democrat demolition dessert dickens diff disaster discrimination discworld dishwasher diskwarrior dixie belle dock doors downing street memo drm dryer drywall dump ed burke eff eggs eject election electric car electric truck electrical electricity elvgren email energy efficiency eric meyer esr etext euthanasia facebook family faq faux news feed feedreader fence finder firefox first4internet first amendment fishmeal flash flickr flooring foreign exchange foundation fox and goose framing freebsd freedback fyq garage garden geek geotag geourl gnutar go gonuls google google earth google maps gpl gracenote graywater greek green group concat gtd gunthers gutters gwbush gymnastics hacking halloween handspring hardwood harry potter headmeta high speed photograph high tech inv hoax hobbies hobby hodgins holiday holly home power magazine horcrux houseblogs how to html humor hvac ilovejackdaniels impeach inspection insulation intel internet ipod ipodder iq iraq isight itunes ivins iwantsandy java city javascript joint chiefs joseph jott journalized blue judges cup kctc khs kimkerry kitchen kyocera la salles la times labor landscape laundry law leatherbys legal lego leopard lhc liberal library linkedin ljurban lodi logic logo lungren maaloufs mac macbook mailinator malware map marin markdown mason media media clip media reform meetup metric mexican microsoft mike comfort military milonic mindstorms mlk model railroading modoc hall monterey morning sedition motorcycle movie moving munchkin murray mushroom music mynetflix mysql naked lounge nerd score netflix network new urbanism new year New Yorker nofollow nutella oatmeal obama obcz occidental occupation omni openssl oracle organic osx owp paint pair palast palm panasonic parallels party patch peak adventures peak oil pear pedestrian village perl petaluma php ping pingback pingomatic pingomation pingqueue pirate pl sql planet bike plasma playroom entertainment plugin plugin:preview theme plugin:text control plugin:ultimate tag warrior plumbing podcast podsite politics portupgrade potato powerbook printer programming project gutenberg pryde punk puzzle qiana quilt quilt shop quiz quote r5 records racism radio railroad recent comments recipe redalt remodel resaurant resolution restaurant restore review richmond rio americano robotics roger niello ron montana roof rootkit rss sacbee sacog sacramento sacramento spotlight magazine salad san francisco sandwich santa cruz scam scandal school days scplugin security session report shakespeare shuffle sigma siriradha sitemap snl snopes social social network software soma somafab sonicchicken sonicchicken blog sony spam spam karma spellcheck spinach spirit spoiler etiquette spring hill cheese sql sqlserver stairs standards statcounter stephen king stop loss stucco stunt subversion sudoku superbowl superhero supreme court sushi svn sysadmin tacoma tags plugin takara technology telephone television template terms and conditions textcontrol thai kitchen thanksgiving theater theme theme:borderline chaos theme:elvgren theme:elvgren wordpress google code theme:fluid blue theme:fullwidth theme:head theme:journalized theme:journalized blue theme:psycho theme:redoable theme:sharepoint like theme:simple green theme:spirit theme:steam theme:wuhan theme:yadda theme switcher thomas tigris euphrates tile tinfoil hat toc tofu tower theater training transit transit oriented development tribute u haul uneasy rhetoric university village van zant veterans day video vie viking hobby vote smart w3c wall warboss washer washington post weather web web developer web server wikipedia windows wishlist woodworking wordpress workplace wpblacklist wpgatekeeper wsj yaaarr yard