简体   繁体   English

SQL Server XQuery修改

[英]SQL Server XQuery modify

I am writing a T-SQL UDF and trying to modify an xml variable with values fetched by a cursor. 我正在编写T-SQL UDF,并尝试使用游标获取的值修改xml变量。 The code executes fine, but the modifications of the xml variable doesn't take place. 该代码可以很好地执行,但是不会对xml变量进行修改。

The code goes as follows: 代码如下:

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

The occupieddates readonly input table goes like this: 占用日期只读输入表如下所示:

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

Simply change 只需更改

as last into (/DateBlocks)[1]

to

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

Either you may consider changing result variable declaration as SELECT @xmlresult = '<DateBlocks/>' . 您可以考虑将结果变量声明更改为SELECT @xmlresult = '<DateBlocks/>'

And also you may cosider using for xml statement: 而且您也可以考虑使用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

Seems like you should change 好像你应该改变

...into (/DateBlocks)...

to

...into (/root/DateBlocks)...

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

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