有没有办法在多用户环境中插入没有存储过程的最后一条记录?
我通过vba连接到sql server。我插入一些记录并致电:
SELECT SCOPE_IDENTITY()
这不起作用。它每次都返回null。
这是整个代码:
Dim sqlstring1 As String
sqlstring1 = "delete from batchinfo where datapath='" & dpath & "' and analystname='" & aname & "' and reportname='" & rname & "' and batchstate='" & bstate & "'"
Dim rowid_batchinfo As String
rs.Filter = "datapath='" + dpath + "' and analystname='" + aname + "' and reportname='" + rname + "' and batchstate='" + bstate + "'"
If Not rs.EOF Then
rowid_batchinfo = rs.Fields("rowid")
cn.Execute "delete from batchinfo where rowid=" + rowid_batchinfo
cn.Execute "delete from calibration where rowid='" + rowid_batchinfo + "'"
cn.Execute "delete from qvalues where rowid='" + rowid_batchinfo + "'"
End If
With rs
.AddNew ' create a new record
' add values to each field in the record
.Fields("datapath") = dpath
.Fields("analysistime") = atime
.Fields("reporttime") = rtime
.Fields("lastcalib") = lcalib
.Fields("analystname") = aname
.Fields("reportname") = rname
.Fields("batchstate") = bstate
.Fields("instrument") = instrument
.Update ' stores the new record
End With
Set rs = cn.Execute("SELECT SCOPE_IDENTITY()", , adCmdText)
Set rs = rs.NextRecordset
问题是如何在多用户环境中插入最后一条记录?
答案 0 :(得分:3)
来自docs:
返回插入同一范围内的标识列的最后一个标识值。范围是一个模块:存储过程,触发器,函数或批处理。因此,如果两个语句在同一存储过程,函数或批处理中,则它们在同一范围内。
这意味着您应该使用插入查询在同一批次(即SCOPE_IDENTITY
调用)中发送SQL
。
使用AddNew
等方法无法做到这一点,因此您应使用明确的INSERT
语句,后跟SELECT SCOPE_IDENTITY
。
这样的事情:
SQL = "INSERT INTO mytable (datapath, analysistype, …) VALUES (@datapath, @analysistime, …) SELECT SCOPE_IDENTITY()"
Set cmd = Server.CreateOject("ADODB.Command")
With cmd
.CommandType = adCmdText
.CommandText = SQL
.Parameters.Append .CreateParameter("@datapath", adVarWChar, adParamInput,, dpath)
…
End With
Set rs = cmd.Execute
Set rs = rs.NextRecordset
答案 1 :(得分:1)
这就是我在sp中的用法:
ALTER PROCEDURE [dbo].[usp_app_execSQL_insert] (@SQL AS text)
AS
set nocount on
exec(@sql + ' select scope_identity()')
--select @@identity --works, but returns value from session scope, not insert scope.
--return @@identity --doesn't work
--exec(@sql) return/select scope_identity() -- doesn't work (insert outside scope)