一次将数据插入2个相关表中?
我试图使用第一个表格中的主键立即插入两个表中,以将其插入第二个表中,但我不确定如何处理。
我的表结构如下:
Person
PersonId
FirstName
Surname
员工
EmployeeId
HoursWorked
表是自动增量列。 person> Person
表中的personidSpioreeID
在第二个表中是主要和外键,应与personid
相同。
我一直在尝试使用Google上找到的查询字符串,但运气不多:
string queryString = "BEGIN TRANSACTION DECLARE @DataID int; "
+"INSERT INTO Person(FirstName, Surname) VALUES(@firstName, @surname);"
+ "SELECT @DataID = scope_identity();"
+ "INSERT INTO Employee VALUES(@DataId, @hoursWorked);"
+ "COMMIT";
I am trying to insert into two tables at once using the primary key from the first table to insert into the second but I am not sure how to go about it.
My table structure is as follows:
Person
PersonId
FirstName
Surname
Employee
EmployeeId
HoursWorked
PersonId
in the Person
table is an auto incremented column. EmployeeId
in the second table is a primary and foreign key that should be the same as PersonId
.
I been trying with this query string which I found on Google but with not much luck:
string queryString = "BEGIN TRANSACTION DECLARE @DataID int; "
+"INSERT INTO Person(FirstName, Surname) VALUES(@firstName, @surname);"
+ "SELECT @DataID = scope_identity();"
+ "INSERT INTO Employee VALUES(@DataId, @hoursWorked);"
+ "COMMIT";
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
从C#中,您可以尝试这样的尝试:
update :正如@Charlieface所述,您可以更简单地编写此代码如果您只插入一行 -像这样:
From C#, you can try something like this:
Update: as mentioned by @charlieface, you can write this code more concisely IF you're only ever inserting a single row - like this:
您需要指定要插入的列。
You need to specify the columns you are inserting into.