我目前正在使用Windows窗体应用程序和我的表的SQL Server编写VB.net。我正在创建一个带有两个组合框的订单,一个用于要订购的材料类型,另一个用于名称。底部还有一个提交按钮,用于运行SQL“插入到”代码。材料组合框填充了一组名为“tbl.channel”的SQL表中的材料类型。该列下的每种材料类型都具有与该行关联的部件号,ID和包大小。我希望与该材料类型相关的所有信息都写入一个记录所有订单的新表,用户只需从组合框中选择材料类型。如何使用“从中选择”sql代码将与该材料类型相关的信息提取到一个跟踪所有订购材料的新表中?
Try
Dim connectionstring As String = Nothing
Dim connection As SqlConnection
Dim command As SqlCommand
Dim adapter As New SqlDataAdapter
Dim ds As New DataTable
Dim i As Integer = 0
Dim sql As String = Nothing
connectionstring = "DATA SOURCE = BNSigma\Core ; integrated security = true"
sql = "Select Channel, [Bundle Size], ID from Production.dbo.tblchannel"
connection = New SqlConnection(connstring)
connection.Open()
command = New SqlCommand(sql, connection)
adapter.SelectCommand = command
adapter.Fill(ds)
Catch ex As Exception
MsgBox(ex.ToString)
End Try
Try
Using conn1 As New SqlConnection(connstring)
conn1.Open()
Using comm1 As SqlCommand = New SqlCommand("INSERT INTO Production.dbo.tbl (Channel, OrderedBy, Date1, BundleSize, ID) Values (@Channel, @Orderedby, @getdate(), @BundleSize, @ID)", conn1)
With comm1.Parameters
.AddWithValue("@Channel", CBChannel.SelectedValue)
.AddWithValue("@OrderedBy", CBName.SelectedValue)
.AddWithValue("@BundleSize", CBChannel.SelectedValue)
.AddWithValue("@ID", CBChannel.SelectedValue)
End With
End Using
End Using
Catch ex As Exception
MsgBox("Unable to make SQL connection")
MsgBox(ex.ToString)
End Try
答案 0 :(得分:0)
我不确定我理解你的目标,但是你想要这样做吗?
INSERT Production.dbo.tbl (Channel, OrderedBy, Date1, BundleSize, ID)
SELECT Channel, @Orderedby, getdate(), BundleSize, ID
FROM tbl.channel
WHERE ID = @ID
我很相信你应该只将channel.ID写入订单表 - 你是否有令人信服的理由来编写额外的值?
答案 1 :(得分:0)
SQL允许您使用SELECT查询来填充INSERT语句的值。像这样:
Public Sub PopulateOrder(ByVal MaterialID As Integer, ByVal SalesName As String)
Dim sql As String = "INSERT INTO Production.dbo.tbl (Channel, OrderedBy, Date1, BundleSize, ID) SELECT Channel, @SalesName, current_timestamp, [Bundle Size], ID from Production.dbo.tblchannel WHERE ID = @MaterialID"
Using cn As New SqlConnection("connection string here"), _
cmd As New SqlCommand(sql, cn)
'Better to declare a specific database type than let .AddWithValue() try to infer one for you
cmd.Parameters.Add("@SalesName", SqlDbType.NVarChar, 50).Value = SalesName
cmd.Parameters.Add("@MaterialID", SqlDbtype.Int).Value = MaterialID
cn.Open()
cmd.ExecuteNonQuery()
End Using
End Sub
使用与此类似的代码调用它:
PopulateOrder(CBChannel.SelectedValue, CBName.SelectedValue)
但是对于它的价值,在表格中复制这些信息几乎总是一个坏主意。