一个查询中有多个INSERTS

时间:2013-10-10 08:59:20

标签: sql vb.net ms-access

我的sql查询有问题。我想在第一个表中插入一些数据,然后将ID从上次插入复制到同一查询中的另一个表。

我正在粘贴代码,跳过某人会告诉我正确的方法,因为我得到一些“;”错误。

sqL = "INSERT INTO Narocilo(ID_stranke, datum_sprejema, rok_izdobave, status_narocila, dodal) " + " VALUES('" & txt_idstranke.Text & "','" & Format(datum_sprejem.Value, "d. MM. yyyy") & "','" & Format(datum_izdobava.Value, "d. MM. yyyy") & "','" & txtstatus.Text & "','" & cmb_zaposleni.Text & "'); INSERT into ZadnjiID(zvisaj) SELECT @@IDENTITY FROM Narocilo"

2 个答案:

答案 0 :(得分:3)

Access(JET / ACE)不允许在一个查询中使用多个SQL语句。您收到错误是因为您在分号后面添加了第二个语句。 你需要打破你正在做的事情。 @@IDENTITY仍然有效,前提是您不要先断开连接。例如:

 Dim conn As OleDb.OleDbConnection = New OleDb.OleDbConnection(connstr)
 Dim command As New OleDb.OleDbCommand
 conn.Open()
 command.Connection = conn

 command.CommandText = "INSERT INTO Narocilo(ID_stranke, datum_sprejema, rok_izdobave, status_narocila, dodal) " + " VALUES('" & txt_idstranke.Text & "','" & Format(datum_sprejem.Value, "d. MM. yyyy") & "','" & Format(datum_izdobava.Value, "d. MM. yyyy") & "','" & txtstatus.Text & "','" & cmb_zaposleni.Text & "');"

command.ExecuteNonQuery()
command.CommandText = "SELECT @@Identity"
Dim idd As Integer = command.ExecuteScalar
command.CommandText = "Your second INSERT statement using idd as the id here"
command.ExecuteNonQuery()
conn.Close()

@@IDENTITY仅适用于访问中的整数类型自动编号 - 而不是GUID。 作为旁注,您应该真正参数化您的查询以避免SQL注入攻击。

答案 1 :(得分:0)

使用此代码。

 sqL = "INSERT INTO Narocilo(ID_stranke, datum_sprejema, rok_izdobave, status_narocila, dodal) " + " VALUES('" & txt_idstranke.Text & "','" & Format(datum_sprejem.Value, "d. MM. yyyy") & "','" & Format(datum_izdobava.Value, "d. MM. yyyy") & "','" & txtstatus.Text & "','" & cmb_zaposleni.Text & "'); INSERT into ZadnjiID(zvisaj); SELECT @@IDENTITY"

这将返回当前连接的主键AutoIncrement columns值。

如果此表具有Identity列,则它将返回值。

但是为了那个使用SqlCommand.ExecuteScaler,它将返回对象值,你可以将它用于另一个表。

谢谢。