我正在编写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,
)
答案 0 :(得分: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
答案 1 :(得分:1)
好像你应该改变
...into (/DateBlocks)...
到
...into (/root/DateBlocks)...