Search code examples
sqlsql-servert-sqldatetimeprocedure

How to convert string to date in SQL Server


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


Solution

  • 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