Archive for the ‘Code’ Category

Get the first day of the week from a datetime

Friday, February 12th, 2010
select dateadd(d ,-(datepart(weekday,getdate()-1)), getdate())

This is straightforwards: the patepart function extracts the weekday from the date, we remove one from that value, turn it to a negative number and then add it back the datetime. Simple.

Remove the time part of a TSQL datetime

Friday, February 12th, 2010

select cast(floor(cast(getdate() as float)) as datetime)

Basically, we cast the datetime to a float, floor it and convert it back to a datetime. The first step produces a float representation of the datetime in which the date is to the left of decimal place and the time to the right, floor reduces it the lowest whole number and the last cast makes a datetime again.

SQL Server 2005: sp_msForEachDB

Friday, July 24th, 2009

The following storped procedure will execute the print statement for every database that resides upon your SQL Server.

EXEC sp_msForEachDB 'PRINT ''?'''

Neat, eh? ‘Tis an undocumented feature.