SQL,OPENXML和DateTime对话

时间:2009-08-14 15:07:20

标签: sql-server xml sql-server-2005 datetime openxml

我继承了大量的存储过程,这些存储过程将XML块作为唯一参数,然后作者将其破解(使用OPENXML),然后更新一行。

我在更新包含datetime列的表时遇到问题,以下是当前失败的数据片段:

declare @stuff nvarchar (max);

set @stuff =
'<Booking xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">  
  <UpdatedDateTime>2009-08-14T15:32:09.7240556+01:00</UpdatedDateTime>
</Booking>';

declare @iDoc int;

exec sp_xml_preparedocument @idoc OUTPUT, @stuff;

SELECT UpdatedDateTime
    FROM 
        OPENXML(@idoc, '/*')
    WITH
    (
        UpdatedDateTime datetime 'UpdatedDateTime'
    )

运行它会导致以下错误:

  

Msg 241,Level 16,State 1,Line 12

     

转换时转换失败   来自字符串的日期时间。

如何将日期时间从XML片段转换为基于SQL的日期时间?

由于

1 个答案:

答案 0 :(得分:2)

尝试:

declare @stuff nvarchar (max);

    set @stuff =
    '<Booking xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">  
      <UpdatedDateTime>2009-08-14T15:32:09.7240556+01:00</UpdatedDateTime>
    </Booking>';

    declare @iDoc int;

    exec sp_xml_preparedocument @idoc OUTPUT, @stuff;

    SELECT CONVERT(datetime,REPLACE(LEFT(UpdatedDateTime,23),'T',' ')),RIGHT(UpdatedDateTime,6)
        ,CASE
             WHEN LEFT(RIGHT(UpdatedDateTime,6),1)='+' THEN DATEADD(hh,CONVERT(int,LEFT(RIGHT(UpdatedDateTime,5),2)),CONVERT(datetime,REPLACE(LEFT(UpdatedDateTime,23),'T',' ')))
             ELSE DATEADD(hh,-1*CONVERT(int,LEFT(RIGHT(UpdatedDateTime,5),2)),CONVERT(datetime,REPLACE(LEFT(UpdatedDateTime,23),'T',' ')))
         END

        FROM 
            OPENXML(@idoc, '/*')
        WITH
        (
            UpdatedDateTime varchar(100) 'UpdatedDateTime'
        )

结果集:

----------------------- ------ -----------------------
2009-08-14 15:32:09.723 +01:00 2009-08-14 16:32:09.723

(1 row(s) affected)