简体   繁体   English

在字符串中选择一个日期并将其转换为日期时间

[英]Select a date in a string and convert it to datetime

I have a string like:我有一个像这样的字符串:

'SPY US 03/20/20 P45' '间谍美国 03/20/20 P45'

I want to select just the date from the string.我只想从字符串中选择日期。

My current query is:我目前的查询是:

Select Ticker, SUBSTRING(Ticker, PATINDEX('%[0-9][0-9]/[0-9][0-9]/[0-9][0-9]%',o.Ticker),8) AS 'myDate' FROM TABLE

This returns: 'SPY US 03/20/20 P45', 03/20/20这将返回:'SPY US 03/20/20 P45', 03/20/20

I want myDate to be in datetime.我希望 myDate 在日期时间。

I have tried various morphs of cast and convert, but they fail, presumably because they want the format to be in YYYY-MM-DD rather than MM/DD/YY.我尝试了各种类型的转换和转换,但都失败了,大概是因为他们希望格式为 YYYY-MM-DD 而不是 MM/DD/YY。

My "smartest" attempt to convert was this:我“最聪明”的转换尝试是这样的:

CONVERT(DATETIME, SUBSTRING(o.Ticker, PATINDEX('%[0-9][0-9]/[0-9][0-9]/[0-9][0-9]%',o.Ticker),8),1)

After reading style guidelines here: https://www.w3schools.com/sql/func_sqlserver_convert.asp but it still failed.在此处阅读样式指南后: https : //www.w3schools.com/sql/func_sqlserver_convert.asp但它仍然失败。

The ideal end-format for the date would be YYYY-MM-DD日期的理想结束格式是 YYYY-MM-DD

Edited to add:编辑添加:

I have been fiddling with it and realized that I over simplied my question.我一直在摆弄它,并意识到我过于简单化了我的问题。 The convert works if I just test it on a string, but the entire query involves several joins.如果我只是在字符串上测试它,则转换有效,但整个查询涉及多个连接。

As I can understand you are looking for something like this.据我所知,您正在寻找这样的东西。

You can use string_split() function to split string with blank space and then use try_cast() function to check each value whether it is a date .您可以使用string_split()函数用空格分割字符串,然后使用try_cast()函数检查每个值是否为date

declare @string as varchar(120) = 'SPY US 03/20/20 P4'
; with cte as (select 
  value
from string_split (@string, ' ')
)Select value from cte where try_cast (value as datetime) is not null

Live db<>fiddle demo.现场数据库<>小提琴演示。

So it turns out that there were a few entries in the column that didn't have friendly date format, so the patindex clause was returning nonsense.所以事实证明,列中有一些条目没有友好的日期格式,所以 patindex 子句返回的是无意义的。

For some reason that caused the entire operation to fail(rather than just returning null on the few entries that were failing).由于某种原因导致整个操作失败(而不仅仅是在少数失败的条目上返回 null)。

Once I selected the entire (ultimately more complicated join statement) into a temp table, then I was able to try_convert the substring into a date and run my operations.一旦我将整个(最终更复杂的连接语句)选择到一个临时表中,我就可以将子字符串 try_convert 转换为日期并运行我的操作。

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

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