简体   繁体   English

将字符串转换为日期 SQL Server

[英]Convert string to date SQL Server

I have a query when I need to convert a string to datetime, I use当我需要将字符串转换为日期时间时,我有一个查询,我使用

CONVERT(DATETIME, '')

but it's still not working.但它仍然无法正常工作。 My column fechac is of type Datetime .我的列fechacDatetime类型。

If I pass in for example '2019-11-20 00:03:56.120' , the query works but I don't need the time because is a parameter from an application web and I send the date example '2019-11-20'.如果我传入例如'2019-11-20 00:03:56.120' ,则查询有效,但我不需要时间,因为它是来自应用程序网络的参数,我发送日期示例 '2019-11-20 '。 Thanks!谢谢!

This is my query:这是我的查询:

SELECT * 
FROM table 
WHERE cb.fechac = CONVERT(DATETIME, '2019-11-20');

Use the format yyyyMMdd .使用格式yyyyMMdd With the datetime datatype yyyy-MM-dd is ambiguous.对于datetime数据类型yyyy-MM-dd是不明确的。 Otherwise, use a style code :否则,使用样式代码

CONVERT(datetime,'2019-11-20',126);
CONVERT(datetime,'20191120')

Reading a lot through the lines in the comments here, however, are you actually after..?:然而,通过这里的评论中的行阅读了很多,但是,您实际上是在追求..?:

WHERE fechac >= '20191120'
  AND fechac < '20191121'

Final reading through the lines.最后通读一遍。 it appears the OP is actuaklly passing a parameter (I assume of the data type date ), therefore...看来 OP 正在实际传递一个参数(我假设数据类型为date ),因此...

WHERE fechac >= @fechac
  AND fechac < DATEADD(DAY, 1, @fechac)

这应该适用于任何系统,无论国际化设置如何:

WHERE cb.fechac=convert(DATE,'20191120');
SELECT *
FROM table cb
WHERE cast(cb.fechac as date) = convert(date, '2019-11-20', 23)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM