我正在使用TableAdapter将新行插入表中。问题是如何从新插入的行的表中获取密钥?我进行了一些搜索,找到了一些解决方案:
必须声明标量变量@FileName FileName是查询中的第一个字段:
INSERT INTO FileTable
(FileName, DirectoryName, FullPath, Extension, ToolNumber)
VALUES (@FileName,@DirectoryName,@FullPath,@Extension,@ToolNumber);
SELECT SCOPE_IDENTITY();
我的VB.Net代码:
Dim fileRow As ToolsDataSet.FileTableRow
fileRow = ToolsDataSet.FileTable.NewRow()
With fileRow
.FileName = "Test13456789"
End With
ToolsDataSet.FileTable.Rows.Add(fileRow)
FileTableTableAdapter.Update(fileRow)
这肯定是常见需求。
我怎么获得那个钥匙?
答案 0 :(得分:2)
通过将类型化数据表限制为单个表(即:SELECT * FROM FileTable
),该类型化数据表能够注意到IDENTITY COLUMN
并在插入发生后填充它,从而使您可以访问它您的代码。
MSSql测试表
CREATE TABLE [dbo].[Insert_Test](
[Id] [int] IDENTITY(1,1) NOT NULL,
[aString] [varchar](50) NULL,
[aNumber] [int] NULL,
[aBit] [bit] NULL,
[aDate] [datetime] NULL,
[aFloat] [float] NULL,
[aImage] [varbinary](2048) NULL,
CONSTRAINT [PK_Insert_Test] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
VB.Net测试方法
<TestMethod()>
Public Sub TestAddRowWithDataAdapter()
Dim connectionString As String = "Server=.;Database=JVTest;Trusted_Connection=True;"
Using conn As New SqlConnection(connectionString)
conn.Open()
Dim dataAdapter As New JVTestDataSetTableAdapters.Insert_TestTableAdapter()
Dim dt As New JVTestDataSet.Insert_TestDataTable
dataAdapter.Fill(dt)
Debug.Print(dt.Rows.Count)
Dim newRow As JVTestDataSet.Insert_TestRow
newRow = dt.NewInsert_TestRow()
dt.Rows.Add(newRow)
newRow("aString") = "abc"
newRow("aNumber") = 123
newRow("aDate") = DateTime.Now
Dim rowsInserted As Integer = dataAdapter.Update(newRow)
Dim rowId As Integer = newRow.Id
End Using
End Sub
在下一行执行时,返回1,对应于要添加的一行
Dim rowsInserted As Integer = dataAdapter.Update(newRow)
执行下面的行时,.Id
列将包含新的行ID
Dim rowId As Integer = newRow.Id
答案 1 :(得分:0)
使用类型化的数据集时,插入命令的末尾会有一个选择命令,以获取新的值,包括标识列。
因此,在更新后检查identity列的值就足够了:
ToolsDataSet.FileTable.Rows.Add(fileRow)
Dim id = fileRow.Id