简体   繁体   English

带输出子句的插入语句

[英]Insert statement with Output Clause

I have the following two tables: 我有以下两个表:

Game_Information Game_Information

gameId(PK) Is Identity(auto-increments)
gamePrice
name
edition
date

Game_Notes Game_Notes

noteId(PK) Is Identity(auto-increments)
notes
noteDate
gameId(FK)

I'm currently trying to code a cshtml page in WebMatrix that will allow me to add information about my game collection across two tables but I'm having trouble getting the gameId to match across both tables so, multiple notes reference one game. 我目前正在尝试在WebMatrix中编写一个cshtml页面,以允许我在两个表之间添加有关我的游戏收藏的信息,但是我在使gameId在两个表之间都匹配时遇到麻烦,因此,多个注释引用了一个游戏。

I tried the following: 我尝试了以下方法:

var id = db.Execute("INSERT INTO Game_Information (gamePrice, name, edition, addedDate) output Inserted.gameId VALUES (@0, @1, @2, @4)", gamePrice, name, edition, date); 

db.Execute("INSERT INTO Game_Notes(gameId, notes, noteDate) VALUES (@0, @1, @2)", id, notes, noteDate);

Which puts the information into the desired columns but "gameId" inserted into Game_Notes always defaults to "1" instead of the correct id of the newly inserted game. 它将信息放入所需的列中,但插入Game_Notes中的“ gameId”始终默认为“ 1”,而不是新插入的游戏的正确ID。

So I tried the following: 所以我尝试了以下方法:

db.Execute("INSERT INTO Game_Information (gamePrice, name, edition) output Inserted.gameId, Inserted.date INTO Game_Notes(gameId, noteDate) VALUES (@0, @1, @2)", gamePrice, name, edition); 

This inserts the correct id into "gameId", so there is a match between the two tables but now I'm lost as how to get the "notes" variable into that same row. 这会将正确的ID插入“ gameId”,因此两个表之间存在匹配,但是现在我迷失了如何将“ notes”变量放入同一行。 Doing a second Insert is clearly out and going for an Update on the last row of the table doesn't seem like a wise idea. 显然第二遍插入已插入,并且要在表的最后一行进行更新似乎不是一个明智的主意。

Anyone have any tips on what I can do here? 有人对我在这里可以做什么有任何提示吗? I'm thinking restructuring the Insert to accommodate for the Notes variable is the key but I keep hitting a wall on it. 我想重组插入以适应Notes变量是关键,但是我一直在碰壁。

As I said Database.Execute method returns the count of records affected by the SQL statement . 正如我所说的, Database.Execute方法返回受SQL statement影响的记录数。 So you were inserting one row and getting 1 as a result. 因此,您要插入一行并得到1

The Execute method is used to perform non-query commands on a database, such as the SQL Drop, Create, Delete, Update, and Insert commands. Execute方法用于对数据库执行非查询命令,例如SQL Drop,Create,Delete,Update和Insert命令。 https://msdn.microsoft.com/en-us/library/webmatrix.data.database.execute(v=vs.111).aspx https://msdn.microsoft.com/en-us/library/webmatrix.data.database.execute(v=vs.111).aspx

You need Database.QueryValue method that executes a SQL query that returns a single scalar value as the result. 您需要Database.QueryValue方法,该方法执行一个SQL查询,该查询返回一个标量值作为结果。

var id = db.QueryValue(...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM