[英]Sql Server trigger insert values from new row into another table
I have a site using the asp.net membership schema. 我有一个使用asp.net成员资格模式的网站。 I'd like to set up a trigger on the aspnet_users table that inserted the user_id and the user_name of the new row into another table.
我想在aspnet_users表上设置一个触发器,它将user_id和新行的user_name插入到另一个表中。
How do I go about getting the values from the last insert? 如何从最后一次插入中获取值?
I can select by the last date_created but that seems smelly. 我可以选择最后一个date_created,但这看起来很臭。 Is there a better way?
有没有更好的办法?
try this for sql server 试试这个sql server
CREATE TRIGGER yourNewTrigger ON yourSourcetable
FOR INSERT
AS
INSERT INTO yourDestinationTable
(col1, col2 , col3, user_id, user_name)
SELECT
'a' , default , null, user_id, user_name
FROM inserted
go
You use an insert trigger - inside the trigger, inserted row items will be exposed as a logical table INSERTED
, which has the same column layout as the table the trigger is defined on. 您使用插入触发器 - 在触发器内,插入的行项将作为逻辑表
INSERTED
公开,其具有与定义触发器的表相同的列布局。
Delete triggers have access to a similar logical table called DELETED
. 删除触发器可以访问名为
DELETED
的类似逻辑表。
Update triggers have access to both an INSERTED
table that contains the updated values and a DELETED
table that contains the values to be updated. 更新触发器可以访问包含更新值的
INSERTED
表和包含要更新的值的DELETED
表。
In a SQL Server trigger you have available two psdeuotables called inserted and deleted. 在SQL Server触发器中,您有两个名为inserted和deleted的psdeuotable。 These contain the old and new values of the record.
它们包含记录的旧值和新值。
So within the trigger (you can look up the create trigger parts easily) you would do something like this: 因此,在触发器内(您可以轻松查找创建触发器部件),您可以执行以下操作:
Insert table2 (user_id, user_name)
select user_id, user_name from inserted i
left join table2 t on i.user_id = t.userid
where t.user_id is null
When writing triggers remember they act once on the whole batch of information, they do not process row-by-row. 在编写触发器时记住它们对整批信息执行一次,它们不会逐行处理。 So account for multiple row inserts in your code.
因此,在代码中考虑多行插入。
When you are in the context of a trigger you have access to the logical table INSERTED which contains all the rows that have just been inserted to the table. 当您处于触发器的上下文中时,您可以访问逻辑表INSERTED,其中包含刚刚插入表中的所有行。 You can build your insert to the other table based on a select from Inserted.
您可以根据从Inserted中选择的内容将插入内容构建到另一个表。
Create
trigger `[dbo].[mytrigger]` on `[dbo].[Patients]` after update , insert as
begin
--Sql logic
print 'Hello world'
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.