2
以下のケースでは、ストアドプロシージャを使用する際に助けが必要です。フィールドがVoucherCode
とQuantity
の単一XML列のテーブルがあり、SQL xml列のデータは次のようになりますこれ:ストアドプロシージャの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
バックトラックa litt 1つのテーブルにVoucherCode
とQuantity
というカラムがあり、今はXMLカラムで、VoucherCode
とQuantity
の両方の値をカプセル化していますが、私はこの作業用ストアドプロシージャを以下のように書いています私のストアドプロシージャを書き換える方法に失われた、さまざまな方法を試してみましたが、どうやら私はしてくださいアドバイス、ありがとう!:
ALTER PROCEDURE [dbo].[Campaign_InsertRewardsVoucher]
@VoucherCode nvarchar(50) =NULL,
@Quantity int = NULL
[email protected] int = NULL
AS
BEGIN
DECLARE @ExistingQuantity Int = Null
IF EXISTS (SELECT * FROM ForTest_Campaign_Voucher WHERE [email protected])
BEGIN
SET @ExistingQuantity = (SELECT Quantity from ForTest_Campaign_Voucher Where [email protected])
SET @ExistingQuantity = (@ExistingQuantity + @Quantity)
UPDATE ForTest_Campaign_Voucher SET [email protected], [email protected] Where [email protected]
END
ELSE
INSERT INTO ForTest_Campaign_Voucher(VoucherCode, Quantity) VALUES(@VoucherCode, @Quantity)
END