Home > OS >  How to convert string to date in SQL Server
How to convert string to date in SQL Server

Time:09-23

I have a table named UserLog as shown here. How can I write a procedure to find the specified data in the table?

I have created the following procedure; but it doesn't work:

CREATE PROCEDURE [dbo].[Sp_CleanUserLogTable]
    @FromDate date,
    @ToDate date
AS
    DELETE FROM UserLog 
    WHERE TRY_CAST(EnterDate AS date) >= @FromDate 
      AND TRY_CAST(EnterDate AS date) <= @ToDate 

enter image description here

CodePudding user response:

Format the date as yyyy-MM-dd. eg 2021-09-23

CodePudding user response:

There is no date format that exactly matches your text, but you can use REPLACE to get a different format:

TRY_CONVERT(datetime, REPLACE(EnterDate, '.', '-'), 105)

This is one of the many reasons why you should always store data in the correct data type in the first place

  • Related