在SQL Server中转换varchar日期格式时的日期时间转换错误

时间:2019-03-13 05:45:49

标签: sql sql-server tsql

我想将此日期时间格式'01/02/2019 12:00:00 AM'转换为
'2019-02-01'格式。

我已经编写了这段代码:

declare @start_date datetime;
declare @end_date datetime;

set @start_date = '01/02/2019 12:00:00 AM';
set @end_date = '28/02/2019 12:00:00 AM';

select * 
from test 
where [Global Dimension 1 Code] in ('FIN') 
  and convert(char(10), [Posting Date], 126) between convert(date, convert(char(10), @start_date, 126), 103)  
                                                 and convert(date, convert(char(10), @end_date, 126), 103)

但是我遇到了错误

  

Msg 242,第16级,状态3,第8行
  将varchar数据类型转换为datetime数据类型会导致超出范围的值。

     

第241条消息,第16级,状态1,第10行
  从字符串转换日期和/或时间时转换失败。

但是当我按如下所示运行查询时,该查询已正确执行。

select * 
from test 
where [Global Dimension 1 Code] in ('FIN') 
  and convert(char(10), [Posting Date], 126) between convert(date, convert(char(10), '01/02/2019 12:00:00 AM', 126), 103) 
                                                 and convert(date, convert(char(10), '28/02/2019 12:00:00 AM', 126), 103)

2 个答案:

答案 0 :(得分:1)

在下面与cast()format()一起使用-将可在sql server 2012+上运行

DEMO

select format(cast('01/02/2019 12:00:00 AM' as date),'yyyy-MM-dd')

答案 1 :(得分:1)

使用103

SELECT convert(char(10), '01/02/2019 12:00:00 AM', 126)

$(document).on("click", ".deleteIcon", function() {
  // get the parent tr element and remove
  $(this).closest('tr').remove();
});
相关问题