我有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