在SQL Server中转换日期

时间:2016-11-28 10:49:48

标签: sql sql-server sql-server-2008

我试图在CreatedDate的基础上进行比较,但它给我一个错误,如

  

将varchar数据类型转换为日期时间数据类型会导致超出范围的值

这是我的查询@startdate和@endDate是我的存储过程的参数。

declare @startDate as varchar(100) = null
declare @endDate as varchar(100) = null
set @startDate = '01/11/2016'
set @endDate = '30/11/2016'

SELECT CreatedDate FROM Table1 
WHERE HCCreatedDate BETWEEN 
CONVERT(Datetime, ISNULL(@startDate,''), 103)
    AND CONVERT(Datetime, ISNULL(@endDate,''), 103) 

2 个答案:

答案 0 :(得分:1)

请转换HCCreatedDate列,如下所示

declare @startDate as varchar(100) = null
declare @endDate as varchar(100) = null
set @startDate = '01/11/2016'
set @endDate = '30/11/2016'

SELECT 
    CreatedDate 
FROM 
    Table1 
WHERE 
    CONVERT(DATETIME,HCCreatedDate,103) BETWEEN CONVERT(DATETIME, ISNULL(@startDate,''), 103) AND CONVERT(DATETIME, ISNULL(@endDate,''), 103) 

答案 1 :(得分:0)

同时将您的专栏改为日期时间。然后再试一次

declare @startDate as varchar(100) = null
declare @endDate as varchar(100) = null
set @startDate = '01/11/2016'
set @endDate = '30/11/2016'

SELECT CreatedDate FROM Table1 
WHERE CONVERT(DATETIME, HCCreatedDate), 103)BETWEEN 
CONVERT(DATETIME, ISNULL(@startDate,''), 103)
    AND CONVERT(DATETIME, ISNULL(@endDate,''), 103)