Handling date in SQL Server

后端 未结 2 1999
面向向阳花
面向向阳花 2020-12-12 06:54

I am working on a website in asp.net. I am getting a date from a web page and then depending on the user input I want to get results from SQL Server database (using stored p

相关标签:
2条回答
  • 2020-12-12 07:20

    If you only want compare with day level and ignoring the hours part, you can use DateDiff function. Pass d or DAY to interval parameter of DateDiff

    For example:

    DECLARE @sDate VARCHAR(100)='2016-10-08'
    IF ISDATE(@sDate)=1
    BEGIN
       select * 
       from table 
       where datediff(d,acceptedDate,@sDate)=0  --same day
    END
    ELSE 
     PRINT 'Invalid date format!'
    
    0 讨论(0)
  • 2020-12-12 07:25

    Don't pass dates as strings. Pass them as DateTime.
    The .Net DateTime maps directly to SQL Server's DateTime. All you have to do is parse the string to a DateTime struct in your .Net code and pass it as a parameter to your stored procedure. To search for a specific date and ignore the Time portion of the DateTime, better use >= and < in your sql:

    select * 
    from table 
    where acceptedDate >= @Date
    AND acceptedDate < DATEADD(DAY, 1, @Date);
    
    0 讨论(0)
提交回复
热议问题