DateTime query on only year in SQL Server

前端 未结 8 1615
灰色年华
灰色年华 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'
    
    0 讨论(0)
  • 2021-01-12 08:20

    Yes, if you try this query:

    SELECT to_date ('2008','yyyy') AS my_date, SYSDATE FROM dual;
    

    The date will be the year (2008) and the current month (today is November), and the day is 1 so your query do not includes all months in 2008.

    0 讨论(0)
  • 2021-01-12 08:21
    select id,name,bookyear from tab1 where year(bookyear) = 2009
    
    0 讨论(0)
  • 2021-01-12 08:27

    You can do

    ....
    WHERE [IssueDate] > '2004' AND [IssueDate] < 2010
    
    0 讨论(0)
  • 2021-01-12 08:29

    One of the most important things to remember with regards to SQL Server and dates is that the best format to use is this: 'YYYYMMDD' (or 'YYYYMMDD HH:MI:SS'). This format will always be interpreted properly by SQL Server, regardless of regional date settings.

    SELECT [ACCNO] 
          ,[Roll No] 
          ,[IssueDate] 
          ,[DueDate] 
      FROM [test1].[dbo].[IssueHis$]  
     WHERE [IssueDate] >= '20090101' 
       AND [IssueDate] < '20100101'
    
    0 讨论(0)
  • 2021-01-12 08:29
    where YEAR(IssueDate) = '2009'
    

    Reference

    0 讨论(0)
提交回复
热议问题