DateTime query on only year in SQL Server

前端 未结 8 1702
灰色年华
灰色年华 2021-01-12 08:01

I want to select multiple records on the basis of a matching year, for example in table tab where columns are [id] int, [name] varchar, [boo

8条回答
  •  孤独总比滥情好
    2021-01-12 08:12

    1. You need to delimit datetime constants like you would a string
    2. Use yyyymmdd pattern for SQL Server (not yyyy-mm-dd, it is unsafe generally)
    3. Use proper range queries to allow for time value

    So, to find values between "12 Dec 2004" and "31 Dec 2009" inclusive, allowing for time:

    ...
    where [IssueDate] >= '20041212' AND [IssueDate] < '20100101'
    

    Edit, or this, because of the ambiguity in the question for "year = 2009"

    ...
    where [IssueDate] >= '20090101' AND [IssueDate] < '20100101'
    

提交回复
热议问题