在存储为Varbinary的SQL字段中修改XML

时间:2018-10-18 09:31:45

标签: sql-server xml tsql casting dml

我的XML作为varbinary存储在字段中。

Dim selectSlots As String = " select distinct time,process,oven ,line, substring (process,8,3) as process1 from table5 Where  process like '%slots =%' and oven ='15'  order by oven ,line"

Dim AdpterselectSlots As New SqlDataAdapter(selectSlots, con1)
Dim DtselectSlots As New DataTable()
AdpterselectSlots.Fill(DtselectSlots)

Dim sortSLots = DtselectSlots.Rows.Count
Dim count = 0

For x As Integer = 0 To sortSLots - 1

    If DtselectSlots.Rows(x).Item("process1") >= 1 And DtselectSlots.Rows(x).Item("process1") <= 53 Then

        Dim line = DtselectSlots.Rows(x).Item("line") - 1
        Dim selectLots As String = "select distinct time,process,oven ,line, substring (process,48,23) as process1 from table5 Where  process like '%''QCheck'' Button%' and oven ='15' and line = '" & line & "'  "
        Dim Adpterselectlots As New SqlDataAdapter(selectLots, con1)
        Dim Dtselectlots As New DataTable()
        Adpterselectlots.Fill(Dtselectlots)
        Dim lotID = Dtselectlots.Rows(0).Item("process1")
        Dim lotID1 = lotID.Trim()

        Dim cmd1 As New SqlCommand("insert into chamber1([lotnumber] ,[Oven],[line]) values ( @line , @line1,@line2 )", con1)
        cmd1.Parameters.Add("@line", SqlDbType.NVarChar).Value = lotID1
        cmd1.Parameters.Add("@line1", SqlDbType.NVarChar).Value = "15"
        cmd1.Parameters.Add("@line2", SqlDbType.NVarChar).Value = line
        con1.Open()
        cmd1.ExecuteNonQuery()
        con1.Close()
    End If
Next

我想更新一个属性(如下)。但是,错误是“无法在varbinary(max)上调用方法”。我尝试了多种方法来投射它,但找不到。

谢谢

SELECT  cast (inboxXml as xml) FROM globalDB.Inbox WHERE inboxCId = '207435-N'

1 个答案:

答案 0 :(得分:1)

第一个问题是:为什么将XML存储在VARBINARY列中?

这是缓慢,笨拙和错误的...

第二件事是:.modify()仅适用于真正的本地XML inboxXml.modify()CAST(inboxXml AS XML).modify()都不起作用...

这是将列的类型更改为XML的另一个原因...

尝试一下:

DECLARE @tbl TABLE(ID INT IDENTITY,YourXml VARBINARY(MAX));

DECLARE @SomeXML XML='<root><someNode someAttr="test">content</someNode></root>';

INSERT INTO @tbl VALUES(CAST(@SomeXML AS VARBINARY(MAX)));

-这有效

SELECT ID
      ,YourXml
      ,CAST(YourXml AS XML)
FROM @tbl
WHERE ID=1;

-但这是不允许的

UPDATE @tbl SET CAST(YourXml AS XML).modify('replace value of (/root/someNode/@someAttr)[1] with "blah"')
WHERE ID=1

-您可以做什么:

DECLARE @intermediateXML XML= (SELECT CAST(YourXml AS XML) FROM @tbl WHERE ID=1);
SET @intermediateXML.modify('replace value of (/root/someNode/@someAttr)[1] with "blah"');
UPDATE @tbl SET YourXml=CAST(@intermediateXML AS VARBINARY(MAX)) WHERE ID=1;

--voila!
SELECT ID
      ,YourXml
      ,CAST(YourXml AS XML)
FROM @tbl
WHERE ID=1;