2

我正在编写 T-SQL UDF 并尝试使用游标获取的值修改 xml 变量。代码执行得很好,但是 xml 变量的修改没有发生。

代码如下:

CREATE FUNCTION GetDateBlockXmlFromTable(@occupieddates occupieddates READONLY)
RETURNS XML
AS
BEGIN
   DECLARE @xmlresult xml;
   DECLARE @datefrom datetime, @dateto datetime;

   SELECT @xmlresult = '<root><DateBlocks/></root>';

   DECLARE GetDateBlockXmlFromTable_Cur 
   CURSOR FOR 
        SELECT DateFrom, DateTo FROM @occupieddates

   OPEN GetDateBlockXmlFromTable_Cur 

   FETCH NEXT FROM GetDateBlockXmlFromTable_Cur INTO @datefrom, @dateto

   WHILE @@FETCH_STATUS = 0
   BEGIN
      SET @xmlresult.modify('insert <DateBlock><FirstDay>"{sql:variable("@datefrom")}"</FirstDay><EndDay>"{sql:variable("@dateto")}"</EndDay></DateBlock> as last into (/DateBlocks)[1]');

      FETCH NEXT FROM GetDateBlockXmlFromTable_Cur INTO @datefrom, @dateto
   END

   CLOSE GetDateBlockXmlFromTable_Cur
   DEALLOCATE GetDateBlockXmlFromTable_Cur

   RETURN @xmlresult;
END

占用日期只读输入表如下所示:

CREATE TYPE occupieddates  AS TABLE 
(
   DateFrom datetime, 
   DateTo datetime, 
)
4

2 回答 2

3

简单地改变

as last into (/DateBlocks)[1]

as last into (/root/DateBlocks)[1]

您可以考虑将结果变量声明更改为SELECT @xmlresult = '<DateBlocks/>'.

你也可以考虑使用for xml语句:

CREATE FUNCTION GetDateBlockXmlFromTable(@occupieddates occupieddates READONLY)
RETURNS XML
AS
BEGIN
    DECLARE @xmlresult xml;

    set @xmlresult = (
        select
            (select
                '"' + convert(varchar, DateFrom, 126) + '"'  as FirstDay,
                '"' + convert(varchar, DateTo, 126) + '"' as EndDay
            from
                @occupieddates
            for xml path('DateBlock'), type)
        for xml path('DateBlocks')--, root('root') -- depending on need
    )

    return @xmlresult;
END
于 2013-07-05T12:14:40.640 回答
1

看来你应该改变

...into (/DateBlocks)...

...into (/root/DateBlocks)...
于 2013-07-05T12:15:52.413 回答