Click here to monitor SSC
SQLServerCentral is supported by Redgate
 
Log in  ::  Register  ::  Not logged in
 
 
 

Get your favorite SSC scripts directly in SSMS with the free SQL Scripts addin. Search for scripts directly from SSMS, and instantly access any saved scripts 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: 429 | 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