简体   繁体   English

将XML日期时间转换为SQL Server时间戳

[英]Convert XML datetime to SQL server timestamp

I have a XML file where i have a date child with this format: 1958-07-11+01:00 我有一个XML文件,其中有一个日期子格式为: 1958-07-11+01:00

Currently I import this as plain text to my SQL Server, but I would like for my SQL database to understand this, so I can select only the last 7 days for my search. 目前,我将其作为纯文本导入到SQL Server中,但是我希望SQL数据库能够理解这一点,因此我只能选择最近7天进行搜索。 How do I convert this to a time-format my SQL Server understands and how do I then output only the rows with a change date in the last 7 days? 如何将其转换为SQL Server可以理解的时间格式,然后仅输出最近7天内具有更改日期的行? Thanks! 谢谢!

If you can influence the generation of the XML you have to deal with, I'd suggest to write your dates in a proper way into the XML (ISO8601). 如果您可以影响必须处理的XML的生成,建议您以适当的方式将日期写入XML(ISO8601)。

But nevertheless you can go on with what you have: 但是,尽管如此,您可以继续进行以下操作:

declare @xml XML=
'<root>
    <node yourdate="1958-07-11+01:00">Some value for 1958-07-11</node>
</root>';

SELECT @xml.value('(/root/node/@yourdate)[1]','datetime') AS YourDate --Look at the time shift!

--and now, how to filter this
declare @xmlMany XML=
'<root>
    <node yourdate="1958-07-11+01:00">Some value for 1958-07-11</node>
    <node yourdate="1999-07-23+01:00">Some value for 1999-07-11</node>
    <node yourdate="2016-01-13+01:00">Some value for 2016-01-13</node>
    <node yourdate="2016-01-12+01:00">Some value for 2016-01-12</node>
</root>';

WITH AllNodes AS
(
    SELECT One.Node.value('@yourdate','datetime') AS YourDate
          ,One.Node.value('.','varchar(max)') AS NodeValue
    FROM @xmlMany.nodes('/root/node') AS One(Node)
)
SELECT * 
FROM AllNodes
WHERE YourDate> GETDATE()-7

You should save this value as a datetime. 您应该将此值另存为日期时间。 This is more convenient and according to conventions. 按照惯例,这更加方便。 Do the next steps: 请执行以下步骤:

  1. Replace your varchar column with datetime. 将您的varchar列替换为datetime。

  2. Convert all the values that you have to save it as the new type. 转换将其保存为新类型所需的所有值。

    convert(datetime, 'Oct 23 2016 11:02:44:013AM', 109)

or 要么

`convert(datetime, "your string datetime value drew from xml file", 109).`

This will convert your string date value into an sql datetime value. 这会将您的字符串日期值转换为sql datetime值。

  1. Select your 7 last days values as it is required. 根据需要选择最后7天的值。

    select * from table where convert(datetime, date, 101) between (Getdate() - 6) and Getdate() order by date

  2. In the future you should convert your values to datetime before saving. 以后,您应该在保存之前将值转换为日期时间。

Another way is to parse the varchar value, convert the values to the integer type and order this using required conditions. 另一种方法是解析varchar值,将值转换为整数类型,然后使用所需条件对其进行排序。 But I think this is not good approach. 但是我认为这不是一个好方法。

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

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