一对多关系的 INSERT 语句
INSERT statement for One to Many relationship
所以我正在做一个项目来为我的游戏编目,我 运行 遇到了一个问题。我有一个包含两个表的数据库,细分如下:
Game_Information
- gameId(PK) 是身份(自增)
- 游戏价格
- 名字
- 版本
Game_Notes
- noteId(PK) 是身份(自增)
- 笔记
- 笔记日期
- gameId(FK)
一个游戏可以有很多笔记,所以两个表之间存在一对多的关系,其中 "Game_Notes" 中称为 "gameId" 的列是 FK/references [的主键=55=]同名
现在在 Webmatrix 中,我编写了一个页面,可以让我输入游戏的价格、名称和版本。在同一页面中,我还可以添加有关游戏的注释。在 post 上,页面从文本框中获取信息并尝试执行以下操作:
db.Execute("INSERT INTO Game_Information (gamePrice, name, edition) VALUES (@0, @1, @2)", gamePrice, name, edition);
db.Execute("INSERT INTO Game_Notes(notes, noteDate) VALUES (@0, @1)", notes, noteDate);
现在可以正常工作并将信息放入正确的表格中,但 "Game_Notes" 中的 gameId(FK) 为空。
我想要的是 "Game_Information" 中分配给 gameId(PK) 的编号反映在 "Game_Notes" 中的 gameId(FK)。
任何人都可以帮助我解决这个问题或指出我可以阅读的文章吗?谢谢
-更新-
让问题更清晰。
您需要在第二个 db.execute 语句中包含 gameId
db.Execute("INSERT INTO Game_Notes(gameId, notes, noteDate) VALUES (@0, @1, @2)", gameId, notes, noteDate);
如果我对你的问题的理解正确,那么你正试图完成两件事:
- 获取Game_Information中新插入记录的gameId
- 在下面的插入语句中使用那个 gameId 到 Game_Notes
虽然有无数种方法可以做到这一点,但建议使用 "output" 值。类似于:
var id = db.QueryValue("INSERT INTO Game_Information (gamePrice, name, edition) output Inserted.gameId VALUES (@0, @1, @2)", gamePrice, name, edition);
查看一些帖子以获取更多信息:Sql Server return the value of identity column after insert statement
然后,在以下语句中使用该 ID:
db.Execute("INSERT INTO Game_Notes(gameId, notes, noteDate) VALUES (@0, @1, @2)", id, notes, noteDate);
免责声明:我尚未对此进行任何测试,只是想为您指明正确的方向。
所以我正在做一个项目来为我的游戏编目,我 运行 遇到了一个问题。我有一个包含两个表的数据库,细分如下:
Game_Information
- gameId(PK) 是身份(自增)
- 游戏价格
- 名字
- 版本
Game_Notes
- noteId(PK) 是身份(自增)
- 笔记
- 笔记日期
- gameId(FK)
一个游戏可以有很多笔记,所以两个表之间存在一对多的关系,其中 "Game_Notes" 中称为 "gameId" 的列是 FK/references [的主键=55=]同名
现在在 Webmatrix 中,我编写了一个页面,可以让我输入游戏的价格、名称和版本。在同一页面中,我还可以添加有关游戏的注释。在 post 上,页面从文本框中获取信息并尝试执行以下操作:
db.Execute("INSERT INTO Game_Information (gamePrice, name, edition) VALUES (@0, @1, @2)", gamePrice, name, edition);
db.Execute("INSERT INTO Game_Notes(notes, noteDate) VALUES (@0, @1)", notes, noteDate);
现在可以正常工作并将信息放入正确的表格中,但 "Game_Notes" 中的 gameId(FK) 为空。
我想要的是 "Game_Information" 中分配给 gameId(PK) 的编号反映在 "Game_Notes" 中的 gameId(FK)。
任何人都可以帮助我解决这个问题或指出我可以阅读的文章吗?谢谢
-更新- 让问题更清晰。
您需要在第二个 db.execute 语句中包含 gameId
db.Execute("INSERT INTO Game_Notes(gameId, notes, noteDate) VALUES (@0, @1, @2)", gameId, notes, noteDate);
如果我对你的问题的理解正确,那么你正试图完成两件事:
- 获取Game_Information中新插入记录的gameId
- 在下面的插入语句中使用那个 gameId 到 Game_Notes
虽然有无数种方法可以做到这一点,但建议使用 "output" 值。类似于:
var id = db.QueryValue("INSERT INTO Game_Information (gamePrice, name, edition) output Inserted.gameId VALUES (@0, @1, @2)", gamePrice, name, edition);
查看一些帖子以获取更多信息:Sql Server return the value of identity column after insert statement
然后,在以下语句中使用该 ID:
db.Execute("INSERT INTO Game_Notes(gameId, notes, noteDate) VALUES (@0, @1, @2)", id, notes, noteDate);
免责声明:我尚未对此进行任何测试,只是想为您指明正确的方向。