如果你只是想(一)插入一條記錄到表;(二)使用DataSet和(c)不使用存儲過程,那麼你可以遵循這樣的:
創建dataAdapter,但在select語句中添加WHERE 1 = 0,這樣就不必下載整個表格 - 性能可選步驟
使用作用域標識select語句和輸出參數創建自定義INSERT語句。
做正常的處理,填充數據集,添加記錄和保存表更新。
現在應該能夠直接從參數中提取標識。
例子:
'-- post a new entry and return the column number
' get the table stucture
Dim ds As DataSet = New DataSet()
Dim da As SqlDataAdapter = New SqlDataAdapter(String.Concat("SELECT * FROM [", fileRegisterSchemaName, "].[", fileRegisterTableName, "] WHERE 1=0"), sqlConnectionString)
Dim cb As SqlCommandBuilder = New SqlCommandBuilder(da)
' since we want the identity column back (FileID), we need to write our own INSERT statement
da.InsertCommand = New SqlCommand(String.Concat("INSERT INTO [", fileRegisterSchemaName, "].[", fileRegisterTableName, "] (FileName, [User], [Date], [Table]) VALUES (@FileName, @User, @Date, @Table); SELECT @FileID = SCOPE_IDENTITY();"))
da.InsertCommand.UpdatedRowSource = UpdateRowSource.FirstReturnedRecord
With da.InsertCommand.Parameters
.Add("@FileName", SqlDbType.VarChar, 1024, "FileName")
.Add("@User", SqlDbType.VarChar, 24, "User")
.Add("@Date", SqlDbType.DateTime, 0, "Date")
.Add("@Table", SqlDbType.VarChar, 128, "FileName")
' allow the @FileID to be returned back to us
.Add("@FileID", SqlDbType.Int, 0, "FileID")
.Item("@FileID").Direction = ParameterDirection.Output
End With
' copy the table structure from the server and create a reference to the table(dt)
da.Fill(ds, fileRegisterTableName)
Dim dt As DataTable = ds.Tables(fileRegisterTableName)
' add a new record
Dim dr As DataRow = dt.NewRow()
dr("FileName") = fileName
dr("User") = String.Concat(Environment.UserDomainName, "\", Environment.UserName)
dr("Date") = DateTime.Now()
dr("Table") = targetTableName
dt.Rows.Add(dr)
' save the new record
da.Update(dt)
' return the FileID (Identity)
Return da.InsertCommand.Parameters("@FileID").Value
但是那很長篇大論的做同樣的事情,因爲這...
' add the file record
Dim sqlCmd As SqlCommand = New SqlCommand(String.Concat("INSERT INTO [", fileRegisterSchemaName, "].[", fileRegisterTableName, "] (FileName, [User], [Date], [Table]) VALUES (@FileName, @User, @Date, @Table); SELECT SCOPE_IDENTITY();"), New SqlConnection(sqlConnectionString))
With sqlCmd.Parameters
.AddWithValue("@FileName", fileName)
.AddWithValue("@User", String.Concat(Environment.UserDomainName, "\", Environment.UserName))
.AddWithValue("@Date", DateTime.Now())
.AddWithValue("@Table", targetTableName)
End With
sqlCmd.Connection.Open()
Return sqlCmd.ExecuteScalar
只爲參考:(代碼項目的文章「[與CommandBuilder的和DataAdapter使用SCOPE_IDENTITY] http://www.codeproject.com/Tips/288850/Using-SCOPE- IDENTITY-with-CommandBuilder-and-DataA)「是幫助我的解決方案。 (我不是這篇文章的作者)。 – 2014-10-22 14:47:23
我知道這是舊的,但在2015年,這仍然是非常錯誤的。我有同樣的問題,並已使用上述文章中的代碼。對我來說,解決的辦法是將「將ID設置爲SCOPE_IDENTITY()」改爲「SET SCOPE_ID = SCOPE_IDENTITY()」是的我知道沒有真正的區別,但現在由於某種原因再次起作用 – GuidoG 2017-04-10 07:36:40