将时间戳转换为xml

时间:2011-04-27 14:04:05

标签: sql-server xml timestamp

可以执行以下操作:

SELECT SomeTimestampColumn FROM SomeTable FOR XML PATH('')

,结果看起来像一个字符串 例如

<SomeTimestampColumn >AAAAAATJ2y4=</SomeTimestampColumn>

但出于某种原因,SQL不允许我这样做

SELECT CONVERT(xml,SomeTimestampColumn)FROM SomeTable

这里有两个相关的问题:

  1. 还有其他方法(除了XML PATH(''))从sql或
  2. 获取等效字符串
  3. 是否有更好的方法将时间戳捕获/转换为更易操作的字符串(我需要在ac#应用程序之间来回传递它,并将使用它来确定没有其他人改变了该行中的行其间)
  4. 谢谢, 麦克

2 个答案:

答案 0 :(得分:2)

declare @T table(SomeTimestampColumn timestamp, id int)

insert into @T(id) values(1)
insert into @T(id) values(2)

select 
  (select SomeTimestampColumn for xml path('')) as SomeTimestampColumn
from @T

如果您希望列为XML类型

select 
  (select SomeTimestampColumn for xml path(''), type) as SomeTimestampColumn
from @T

或者,如果您只想要值

select
  T1.ID,
  T3.N.value('.', 'varchar(50)') as SomeTimestampColumn
from @T as T1
  cross apply
    (select T1.SomeTimestampColumn for xml path(''), type) as T2(X)
  cross apply
    T2.X.nodes('SomeTimestampColumn') as T3(N)

结果

ID          SomeTimestampColumn
----------- --------------------------------------------------
1           AAAAAAACDZg=
2           AAAAAAACDZk=

转换到Base64,您可以将其转换回来。这是一些可以进行转换的UDF的链接。 http://www.vbforums.com/showthread.php?t=554886

declare @T table(SomeTimestampColumn timestamp, id int)

insert into @T(id) values(1)

declare @Base64 varchar(max)
declare @Binary varbinary(max)

select
  @Binary = T1.SomeTimestampColumn,
  @Base64 = T3.N.value('.', 'varchar(50)')
from @T as T1
  cross apply
    (select T1.SomeTimestampColumn for xml path(''), type) as T2(X)
  cross apply
    T2.X.nodes('SomeTimestampColumn') as T3(N)

select
  @Base64,
  CAST(N'' AS XML).value('xs:base64Binary(xs:hexBinary(sql:variable("@Binary")))', 'VARCHAR(MAX)'),
  @Binary,
  CAST(N'' AS XML).value('xs:base64Binary(sql:variable("@Base64"))', 'VARBINARY(MAX)')

结果:

AAAAAAAAJ3k=    AAAAAAAAJ3k=    0x0000000000002779  0x0000000000002779

答案 1 :(得分:0)

这是你想要做的:

SELECT convert(datetime, SomeTimestampColumn) 
FROM SomeTable FOR XML PATH('SomeTimestampColumn')