我有3個表。 Item
,StockDetail
,Branch
插入多行,基於另一個表列計數
我想一次插入其中的2個。 Item
和StockDetail
表。
Item
有3列= ItemID
,Title
,Price
。
StockDetail
有3列= ItemID
,BranchID
,Stock
。
Branch
has 1 column = BranchID
。
在下面的代碼中,插入到Item
工作正常,但不是爲StockDetail
表,它不插入任何東西!
現在爲StockDetail
如果一切正常,我想與下面的條件將其插入:
如果添加一個項目,然後它會與所有存在BranchID加入這個項目。
這意味着,每個分支都會有這個項目。
e.g:
您添加項目,而
Branch
有3排BranchID
= BR000
,BR001
,BR002
。
它將插入到StockDetail
3行,以及,在一次(單個查詢)
StockDetail
(單個查詢)的完整結果:
ItemID | BranchID | Stock
______________________________
IM000 | BR000 | 0
IM000 | BR001 | 0
IM000 | BR002 | 0
的代碼:
'Add function'
'Insert to StockDetail'
Dim theCommand As New SqlCommand
Dim theDataAdapter As New SqlDataAdapter
Dim theDataTable As New DataTable
theCommand.Connection = theConnection
theCommand.CommandText = "INSERT INTO StockDetail VALUES(
'" & Me.TextBox_ItemID.Text & "',
SELECT COUNT(BranchID) FROM Branch,
'0'
)"
theDataAdapter.SelectCommand = theCommand
'Insert to Item'
theCommand.Connection = theConnection
theCommand.CommandText = "INSERT INTO Item VALUES('" & Me.TextBox_ItemID.Text & "', '" & Me.TextBox_Title.Text & "', '" & Me.TextBox_Price.Text & "')"
theDataAdapter.SelectCommand = theCommand
theDataAdapter.Fill(theDataTable)
DataGridView_Item.DataSource = theDataTable
theCommand.Dispose()
theDataAdapter.Dispose()
更新:
下面的代碼會告訴你工作多重INSERT,但不支持BranchID INSERT。
'Insert to StockDetail'
theConnection.Open()
Dim theCommand As New SqlCommand
Dim theDataAdapter As New SqlDataAdapter
theCommand.Connection = theConnection
theCommand.Parameters.Add("@ItemID", SqlDbType.VarChar).Value = Me.TextBox_ItemID.Text
theCommand.CommandText = "INSERT INTO StockDetail(ItemID, BranchID, Stock) SELECT @ItemID, COUNT(Branch.BranchID), '0' FROM Branch GROUP BY Branch.BranchID"
theDataAdapter.SelectCommand = theCommand
Using theDataAdapter
theCommand.ExecuteNonQuery()
theCommand.Parameters.Clear()
theCommand.Dispose()
theConnection.Close()
SqlConnection.ClearPool(theConnection)
End Using
現在我該怎麼想?
不是插入1
,1
,。 。 。
我想用BR000
,BR001
來插入它。 。 。 (基於所有已存在的BranchID
)
再次......您需要參數化這些查詢。繼續構建這樣的字符串是危險的,也是邊界疏忽。 –
你也應該習慣於指定你想插入的列或者你的代碼非常脆弱。當表更改時,您的查詢被破壞。 –
@SeanLange wtf,我不明白參數化。我不知道btw大聲笑 – bidipeppercrap