sql-serverfunctiondatedatetimesql-convert

Convert datetime to date using a function


I have one column in my database that I need to convert from datetime to the date data type using a SQL Server function. I can't figure out how to get the correct syntax. Could I get some help with the syntax so IntelliSense will stop yelling at me and I can get the query to run?

CREATE FUNCTION fChangeDateFormat (@date01 date)
RETURNS DATE
AS

RETURN(
SELECT
    Convert(DateTime, OrderDate, 101)
FROM
    Orders
WHERE 
    OrderDate = @date01
)

Solution

  • You can use convert as,

    select CONVERT(date,@date01,101) as dd from Orders
    

    If you are using SQl server 2012 + use FORMAT, 'd' is to get the short date format.

    SELECT FORMAT(@date01,'d','en-US') as dd from Orders