Share via

convert string date to date - search

arkiboys 9,711 Reputation points
2022-06-07T06:53:09.49+00:00

Hi,
I am loading data into table...
One of the columns is HireDate which is as string, i.e. 20220530
20220421
20220607
...
Question,
What is the select query to return all rows but for previous month
i.e. where HireDate >= 1st of previous month and HireDate < = last day of previous month

Thank you

Developer technologies | Transact-SQL
Developer technologies | Transact-SQL

A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.

0 comments No comments

Answer accepted by question author

Viorel 127K Reputation points
2022-06-07T12:20:55.203+00:00

Check this condition:

select *
from MyTable
where datediff(month, HireDate, getdate()) = 1

Was this answer helpful?

0 comments No comments

2 additional answers

Sort by: Most helpful
  1. Jingyang Li 5,901 Reputation points Volunteer Moderator
    2022-06-07T15:06:16.93+00:00
    SELECT *
     FROM test
     where  HireDate >=DATEADD(mm, DATEDIFF(mm,0,GETDATE())-1,0)
      and  HireDate <DATEADD(mm, DATEDIFF(mm,0,GETDATE()),0)
    

    Was this answer helpful?

    0 comments No comments

  2. Naomi Nosonovsky 8,906 Reputation points
    2022-06-07T14:07:29.373+00:00
    DECLARE @StartDate DATE = DATEADD(MONTH, DATEDIFF(MONTH, '19000101', CURRENT_TIMESTAMP)-1, '19000101'); -- beginning of the previous month
    DECLARE @EndDate DATE = EOMONTH(@StartDate)
    
    select * from InfoTable where HireDate between @StartDate and @EndDate
    

    Was this answer helpful?

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.