Get row where datetime column = today - SQL server noob

后端 未结 5 924
旧巷少年郎
旧巷少年郎 2020-12-03 04:32

In sql 2005, instead of building a query from dateparts year, month and date,

is there an more succinct way of writing the where clause?

5条回答
  •  情书的邮戳
    2020-12-03 04:52

    I've used a UDF to do this on datetime columns going back to SQL 2000.

    CREATE FUNCTION [dbo].[GETDATENOTIME](@now datetime)
    RETURNS smalldatetime
    AS
    BEGIN
        RETURN (CONVERT(smalldatetime, CONVERT(varchar, @now, 112)))
    END
    

    Usage:

    DECLARE @date smalldatetime
    SET @date = '4/1/10'
    SELECT * FROM mytable WHERE dbo.GETDATENOTIME(date) = @date
    

    Not the most efficient thing in the world (YMMV depending on your table) but it does the job. For tables where I know I'll be selecting based on date-without-time a lot, I'll have a column specifically for that with a default set to dbo.GETDATENOTIME(GETDATE()).

提交回复
热议问题