为什么我在修改 Sql 中的 Xml 值时收到 Mutator 错误

Why do I receive a Mutator error when modifying an Xml value in Sql

我有以下存储过程:

ALTER PROCEDURE [dbo].[UpPro]
(
    @PN varchar(200),
    @xml xml,
    @gVa varchar(10),
)
AS
/* update the gender */
BEGIN
    SET NOCOUNT ON;

    Select @gVa = t1.[Gender] 
    From [myDb].[dbo].[myTable1] t1 --replace Value2 and table to the table which is updated through SSIS
    Where t1.Name = @PN

    PRINT @gVa //displays 'F'

    Set @xml.modify('replace value of (/root/Phys/gender/text())[1] with sql:variable("@gVa")');
END

/* once all the node has been "temporarily" changed, update the table columns for the provider */
BEGIN
    --update the table after casting dummy xml variable
    Update [myDb].[dbo].[TC]
    Set [chtml] = cast(cast(@xml as nvarchar(max)) as ntext)
    Where [ctitle] = @PN
END

当我运行查询时,出现以下错误:

Msg 5302, Level 16, State 1, Procedure UpPro, Line 115
Mutator 'modify()' on '@xml' cannot be called on a null value.

我该如何解决这个错误。我正在尝试更新 TC table.

ntext 类型的列 (chtml) 中的 xml 值

如果我需要提供更多信息,请告诉我。

只是为了测试代码,我只是尝试了以下,它仍然给出了同样的错误:

DECLARE @gVa varchar(10)
DECLARE @xml xml

Select @gVa = t1.[Gender] 
From [myDb].[dbo].[myTable1] t1 --replace Value2 and table to the table which is updated through SSIS
Where t1.Name = 'Doctor 1'
PRINT @gVa

If @xml IS NOT NULL
BEGIN
    Set @xml.modify('replace value of (/root/Phys/gender/text())[1] with sql:variable("@gVa")');
END
Else
BEGIN
    PRINT 'NOT WORK'
END

继续打印NOT WORK

原始列(chtml)数据:

<?xml version="1.0" encoding="UTF-8"?>
<root>
    <Phys>
        <gender>M</gender>
    </Phys>
</root>

上面的SP执行后,gender应该是F而不是M

错误实际上说明了一切,@XML 为 null,这是不允许的。

转载:

declare @X xml;

set @X.modify('replace value of text()[1] with "1"');

Msg 5302, Level 16, State 1, Line 4 Mutator 'modify()' on '@X' cannot be called on a null value.

修改前检查是否为空。

declare @X xml;

if @X is not null
  set @X.modify('replace value of text()[1] with "1"');