在存储过程中使用XML插入和更新

时间:2011-10-20 04:12:41

标签: asp.net sql sql-server vb.net

我在下面的例子中需要一些使用存储过程的帮助:我有一个带有单个XML列的表,它接受字段VoucherCodeQuantity,SQL xml列中的数据看起来像这样:

<CampaignVoucher xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" VoucherCode="Vouch001" Quantity="2" />

以下方法将调用我的存储过程,根据我的凭证代码检查特定凭证是否存在,然后在我的gridview中添加新行或更新现有凭证:

  Protected Sub btnAdd_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnAdd.Click
        Dim dbCommand As DbCommand = Nothing
        'Dim cmd As New SqlCommand()

        If TextBox1.Text = "" Or DropDownList1.SelectedIndex = 0 Then
            Exit Sub
        End If

        Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("Test").ConnectionString)
        Dim da As New SqlDataAdapter("SELECT CustomerID, VoucherXML FROM Customers", con)

        Dim cmd As New SqlCommand("Campaign_InsertRewardsVoucher_XML", con)
        cmd.CommandType = CommandType.StoredProcedure
        Dim dt As New DataTable()
        da.Fill(dt)

        ' Here we'll add a blank row to the returned DataTable
        Dim dr As DataRow = dt.NewRow()
        dt.Rows.InsertAt(dr, 0)
        'Creating the first row of GridView to be Editable
        GridView1.EditIndex = 0
        GridView1.DataSource = dt
        GridView1.DataBind()
        'Changing the Text for Inserting a New Record
        DirectCast(GridView1.Rows(0).Cells(0).Controls(0), LinkButton).Text = "Insert"



        ' Serialization ----------------------------  

        Dim cm As New CampaignVoucher(DropDownList1.SelectedValue, TextBox1.Text)
        Dim serializer As New XMLserializer(cm.[GetType]())
        Dim memoryStream As New MemoryStream()
        Dim writer As New XmlTextWriter(memoryStream, Encoding.UTF8)

        serializer.Serialize(writer, cm)

        'get the stream from the writer
        memoryStream = TryCast(writer.BaseStream, MemoryStream)

        'apply encoding to the stream 
        Dim enc As New UTF8Encoding()
        Dim xml As String = enc.GetString(memoryStream.ToArray()).Trim()

        ' -------------------------------------------       



        cmd.Parameters.Add("@p1", SqlDbType.VarChar, 50).Value = DropDownList1.SelectedValue
        cmd.Parameters.Add("@p2", SqlDbType.Text).Value = xml

        cmd.Connection = con
        con.Open()
        cmd.ExecuteScalar()
        con.Close()

        GridView1.EditIndex = -1
        BindData()

        TextBox1.Text = ""

    End Sub

回溯一点,我写了这个工作存储过程,如下所示,出于同样的目的只是为了传统存储:1个表格带有VoucherCodeQuantity列,现在有了XML列,现在封装了VoucherCodeQuantity值,我迷失了如何重写我的存储过程,尝试了不同的方法,但显然我搞砸了它,请建议,谢谢!:< / p>

ALTER PROCEDURE [dbo].[Campaign_InsertRewardsVoucher]  
    @VoucherCode   nvarchar(50) =NULL,
    @Quantity           int = NULL
    --@ExistingQuantity   int = NULL

AS  
BEGIN
 DECLARE @ExistingQuantity Int = Null
 IF EXISTS (SELECT * FROM ForTest_Campaign_Voucher WHERE VoucherCode=@VoucherCode)

 BEGIN
    SET @ExistingQuantity = (SELECT Quantity from ForTest_Campaign_Voucher Where VoucherCode=@VoucherCode)
    SET @ExistingQuantity = (@ExistingQuantity + @Quantity)

    UPDATE ForTest_Campaign_Voucher SET VoucherCode=@VoucherCode, Quantity=@ExistingQuantity Where VoucherCode=@VoucherCode
 END
 ELSE
    INSERT INTO ForTest_Campaign_Voucher(VoucherCode, Quantity) VALUES(@VoucherCode, @Quantity)
 END

1 个答案:

答案 0 :(得分:0)

ALTER PROCEDURE [dbo].[Campaign_InsertRewardsVoucher]
    @VoucherCode   nvarchar(50) =NULL,
    @Quantity           int = NULL
AS   
    BEGIN
        DECLARE @ExistingQuantity Int       
        SET @ExistingQuantity = (SELECT xmlFieldName.value('(/CampaignVoucher/@Quantity)[1]', 'int')
                                 FROM ForTest_Campaign_Voucher
                                 WHERE xmlFieldName.value('(/CampaignVoucher/@VoucherCode)[1]', 'nvarchar(50)') = @VoucherCode)
        IF @ExistingQuantity IS NULL
            BEGIN     
                INSERT INTO ForTest_Campaign_Voucher
                    (
                        xmlFieldName
                    )
                VALUES
                    (
                        '<CampaignVoucher xmlns:xsd="http://www.w3.org/2001/XMLSchema" VoucherCode="' + @VoucherCode + '" Quantity="' + CAST(@Quantity AS NVARCHAR(16)) + '" />'
                    )
            END 
        ELSE 
            DECLARE @NewQuantity INT
            SET @NewQuantity = @ExistingQuantity + @Quantity
            UPDATE ForTest_Campaign_Voucher 
            SET xmlFieldName='<CampaignVoucher xmlns:xsd="http://www.w3.org/2001/XMLSchema" VoucherCode="' + @VoucherCode + '" Quantity="' + CAST(@NewQuantity AS NVARCHAR(16)) + '" />'
            WHERE xmlFieldName.value('(/CampaignVoucher/@VoucherCode)[1]', 'nvarchar(50)') = @VoucherCode
    END
GO