[英]How to insert a row into another table using last inserted ID?
I'm having two table on my SQL
server GamerName
and GamerValues
, I want that, when I insert
a new row on GamerName
我在我的
SQL
服务器GamerName
和GamerValues
上有两个表,我想要,当我在GamerName
上insert
一个新行时
GamerName
╔════╦═════════╦
║ ID ║ Name ║
╠════╬═════════╬
║ 1 ║ Jeff ║
║ 2 ║ Geoff ║
║ 3 ║ Jarrod ║
║ 4 ║ Joel Sp ║
╚════╩═════════╩
So, with the last inserted
ID on the table GamerName
, the values should be filled on GamerValues
因此,使用
GamerName
表上最后inserted
ID,应在GamerValues
上填充值
GamerValues
╔════╦══════════════╦════════╗
║ ID ║ GamerID ║ Score ║
╠════╬══════════════╬════════╣
║ 1 ║ 1 ║ 5636 ║
║ 2 ║ 2 ║ 148 ║
║ 3 ║ 3 ║ 101 ║
║ 4 ║ 4 ║ 959 ║
╚════╩══════════════╩════════╝
Is it possible to do it with a single query? 是否可以使用单个查询执行此操作?
You should manage this with a stored procedure. 您应该使用存储过程来管理它。 You can concentrate any additional logic you need when creating a new gamer this way (for example, checking if already exists).
您可以通过这种方式集中创建新游戏玩家所需的任何其他逻辑(例如,检查是否已存在)。
CREATE PROCEDURE dbo.CreateGamer
@Name VARCHAR(100)
AS
BEGIN
IF EXISTS (SELECT 'gamer name already exists' FROM GamerName AS G WHERE G.Name = @Name)
BEGIN
RAISERROR('Gamer name already used!', 16, 1)
RETURN
END
INSERT INTO GamerName (
Name)
VALUES
(@Name)
DECLARE @GamerID INT = SCOPE_IDENTITY()
INSERT INTO GamerValues (
GamerID,
Score)
SELECT
GamerID = @GamerID,
Score = 0
END
You can ensure the uniqueness of the gamer name with a UNIQUE
constraint, I'm just using the EXISTS
to show how you can put additional logic in your SP. 您可以使用
UNIQUE
约束确保游戏者名称的UNIQUE
,我只是使用EXISTS
来展示如何在SP中添加其他逻辑。
You don't need a trigger or any of the @@IDENTITY
, SCOPE_IDENTITY()
functions. 您不需要触发器或任何
@@IDENTITY
, SCOPE_IDENTITY()
函数。 All of them have restrictions and none of them can deal with values that aren't produced by an IDENTITY
constraint. 所有这些都有限制,它们都不能处理
IDENTITY
约束不产生的值。 None of them can deal with multiple insertions either. 它们都不能处理多次插入。
You can use the OUTPUT clause of INSERT
to copy newly inserted values into another table or a table variable. 您可以使用
INSERT
的OUTPUT子句将新插入的值复制到另一个表或表变量中。
OUTPUT is also available for UPDATE and DELETE. OUTPUT也可用于UPDATE和DELETE。 You can retrieve the new/modified columns with the
inserted.
您可以使用
inserted.
方式检索新的/修改的列inserted.
and deleted.
并
deleted.
prefixes 前缀
For these tables : 对于这些表格:
create table #GamerName
(
ID int IDENTITY primary key,
Name nvarchar(20) not null
);
create table #GamerValues(
ID int IDENTITY primary key,
GamerID int not null,
Score int not null
);
You can insert new records in #GamerName
and copy the generated ID to #GamerValues
with : 您可以在
#GamerName
插入新记录,并将生成的ID复制到#GamerValues
:
INSERT INTO #GamerName (Name)
OUTPUT inserted.ID,0 into #GamerValues(GamerID,Score)
VALUES
('Jeff'),
('Geoff'),
('Jarrod'),
New values appear in the inserted
virtual table. inserted
虚拟表中将显示新值。 OUTPUT is also availa OUTPUT也可用
A new line will be created for each of the gamers in GamerValues. 将为GamerValues中的每个玩家创建一个新线。 Let's modify the default score with :
让我们修改默认分数:
UPDATE #GamerValues
SET Score=100
The table will look like : 该表将如下所示:
ID GamerID Score
1 1 100
2 2 100
3 3 100
Adding another gamer with 添加另一个游戏玩家
insert into #GamerName (Name)
output inserted.ID,0 into #GamerValues(GamerID,Score)
Values
('Joel sp')
Will result in a new line with a Score of 0 将得到一个得分为0的新行
ID GamerID Score
1 1 100
2 2 100
3 3 100
4 4 0
You have to add a trigger to this for you. 您必须为此添加触发器。
CREATE TRIGGER newTrigger ON GamerName
FOR INSERT
AS
INSERT INTO GamerValues
(GamerID)
SELECT
'ID'
FROM inserted
GO
Btw the score variable should be set 0 by default since you don't have a value when a new user is created. 顺便说一句,得分变量默认设置为0,因为创建新用户时没有值。 Unless if you do.
除非你这样做。
Hope this helps 希望这可以帮助
If you have an identity column in Gamername Table you can use 如果您在Gamername Table中有一个标识列,则可以使用
INSERT INTO GamerName (Name)VALUES
('Joel Sp');
INSERT INTO GamerValues (GamerID,Score)
SELECT SCOPE_IDENTITY() ,0 score;
If you just need the last column inserted and assuming the gamer id in gamername table are sequential then you can simply use 如果您只需要插入最后一列并假设gamername表中的游戏者ID是顺序的,那么您可以简单地使用
INSERT INTO GamerValues (GamerID,Score)
select max(id),0 score from gamername;
If Nothing Satisfies your condition then TRIGGER is the best Option 如果没有什么能满足您的条件,那么TRIGGER是最佳选择
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.