Click here to monitor SSC
SQLServerCentral is supported by Red Gate Software Ltd.
 
Log in  ::  Register  ::  Not logged in
 
 
 

Get your favourite SSC scripts directly in SSMS with the free SQL Scripts addin. Search for scripts directly from SSMS, and instantly access any saved in your SSC briefcase from the favorites tab.
Download now (direct download link)

UDF to get first date or trim time for Datepart.

By James Travis,

Not long ago I was in a forum discussion when someone presented another way to get the date with time value of midnight by doing similar to this

DATEADD(dd,DATEDIFF(dd,0,@DATE),0)

Which I find is much cleaner than any other option I have seen or tried myself. Seeing this I realized there are many other dates that can be quickly figured by using this method so I researched each.

Well of course I found this much easier to do and decided to collect them all into a simple UDF to make reuse much easier.

First run the below script in the database you want the function available then call like so.

--Get first Sunday of week
select dbo.DateToPart(GETDATE(),'wk')

The valid @PART options are the same as the standard SQL date functions, however if you place a bad item in the date value will be returned untouched. Using the Millisecond option also does the same due to fact there is nothing to do.

Hope this helps out.

(Sorry I don't work much with UDFs and not sure how to throw a custom error, if anyone knows please pass along.)

Total article views: 417 | Views in the last 30 days: 2
 
Related Articles
FORUM

Database Options

Database Options

FORUM

index option

index option

FORUM

Recomplie option

Recomplie option

FORUM

Process Memory Enable options

Process Memory Enable options

FORUM

Full Text search option

Full Text search option

Tags
miscellaneous    
t-sql    
 
Contribute

Join the most active online SQL Server Community

SQL knowledge, delivered daily, free:

Email address:  

You make SSC a better place

As a member of SQLServerCentral, you get free access to loads of fresh content: thousands of articles and SQL scripts, a library of free eBooks, a weekly database news roundup, a great Q & A platform… And it’s our huge, buzzing community of SQL Server Professionals that makes it such a success.

Join us!

Steve Jones
Editor, SQLServerCentral.com

Already a member? Jump in:

Email address:   Password:   Remember me: Forgotten your password?
Steve Jones