我有一個用VB.NET編寫的ASP.NET頁面,通過INNER JOIN
使用SELECT
語句將項目獲取到GridView
,並且還允許您將項目添加到發票。SQL_INSERT和Scope_Identity() - 獲取記錄ID
INNER JOIN
從items
和project_items
獲得數據。
SELECT Items.item_id, Items.item_name, Items.item_cost, project_items.item_quantity
FROM Items
INNER JOIN project_items
ON items.item_id = project_items.item_id
WHERE project_items.project_id = @parameter
@parameter is
Session("ProjectID")
(有一個外鍵project_items.item_id -> items.item_id
。)
我有一個試圖用SQL語句在VB.NET,試圖同時插入到兩個表。我試過是我試圖讓創造的最後一個記錄的item_id
並通過使用數據插入到另一個表(project_items
)。但是,數據僅被輸入到第一個表格中。
任何想法我可以做什麼?
這是代碼:
Protected Sub btnAddItem_Click(sender As Object, e As EventArgs) Handles btnAddItem.Click
Dim conn As New SqlConnection("Data Source=BRIAN-PC\SQLEXPRESS;Initial Catalog=master_db;Integrated Security=True")
Dim addItemComm As String = "SELECT item_id FROM project_items WHERE [email protected]"
Dim user_id_select As New Integer
Dim addItemSQL As New SqlCommand
conn.Open()
addItemSQL = New SqlCommand(addItemComm, conn)
addItemSQL.Parameters.AddWithValue("@ProjectID", Convert.ToInt32(Session("ProjectID")))
Dim datareader As SqlDataReader = addItemSQL.ExecuteReader()
datareader.Close()
conn.Close()
Dim AddNewItemComm As String = "INSERT INTO Items (item_name, item_cost, item_code) VALUES (@ItemName, @ItemCost, @ItemCode); SELECT SCOPE_IDENTITY()"
Dim AddNewItem2Comm As String = "INSERT INTO project_items (item_id, project_id, item_quantity) VALUES (@ItemID, @ProjectID, @ItemQuantity) "
Dim AddNewItemSQL As New SqlCommand
conn.Open()
AddNewItemSQL = New SqlCommand(AddNewItemComm, conn)
AddNewItemSQL.Parameters.AddWithValue("@ItemName", txtItemName.Text.Trim)
AddNewItemSQL.Parameters.AddWithValue("@ItemCost", Convert.ToInt32(txtItemCost.Text))
AddNewItemSQL.Parameters.AddWithValue("@ItemCode", txtItemCost.Text.ToString.ToUpper)
Dim ItemId As Integer
ItemId = AddNewItemSQL.ExecuteScalar()
AddNewItemSQL.ExecuteNonQuery()
conn.Close()
conn.Open()
AddNewItemSQL = New SqlCommand(AddNewItem2Comm, conn)
AddNewItemSQL.Parameters.AddWithValue("@ItemID", ItemId)
AddNewItemSQL.Parameters.AddWithValue("@ProjectID", Convert.ToInt32(Session("ProjectID")))
AddNewItemSQL.Parameters.AddWithValue("@ItemQuantity", Convert.ToInt32(txtItemQuantity.Text))
AddNewItemSQL.ExecuteNonQuery()
conn.Close()
End Sub
你得到任何錯誤??? – mmpatel009
只是用於調試目的的try/catch語句添加到上面的代碼,並檢查是否有任何異常。另外爲什麼關閉/打開兩個命令之間的連接? – Steve
你在調試中一行一行地運行它嗎?你是否從第一個命令中獲得預期的ItemID? –