我想要实现的是我有一个叫做订单的表。 我想在我的订单table.i上执行before insert触发器。我想捕获 执行INSERT到表的人的用户名。 一个名为info的表,其中包含用户。
这是我的代码
create table orders
(
order_id int,
quantity int,
cost int,
total_cost int,
created_date datetime,
created_by varchar(20)
)
create trigger beforeInsertdata
before insert
on orders
for each row
declare
v_username varchar2(10);
begin
-- Find username of person performing INSERT into table
SELECT user INTO v_username
FROM info;
-- Update create_date field to current system date
:new.create_date := sysdate;
-- Update created_by field to the username of the person performing the INSERT
:new.created_by := v_username;
END;
--user information--
create table info
(
userid int ,
user_name varchar(10)
)
insert into info values(1,'vivek')
select * from info
答案 0 :(得分:3)
基本上,触发器分为两种主要类型: -
1)触发后(触发器)
2)取代触发器
,触发器的语法是
CREATE TRIGGER trigger_name ON table_name
[FOR|AFTER|INSTEAD OF] [INSERT|UPDATE|DELETE]
AS
//your code goes here
GO
注意:用于INSERT | UPDATE命令的FOR关键字,其中为AFTER USED FOR DELETE命令。
答案 1 :(得分:0)
很难说出你真正要做的事情。我已修改了您的代码示例,以便它可以在SQL2K5上运行,并对您希望如何使用连接的用户帐户做出一些假设。
CREATE TABLE orders (
order_id int,
quantity int,
cost int,
total_cost int,
created_date datetime,
created_by varchar(20)
);
CREATE TABLE info (
userid int,
user_name varchar(10)
);
INSERT INTO info
VALUES (1, 'vivek');
SELECT *
FROM info;
CREATE TRIGGER orders_InsteadOfInsert ON orders
INSTEAD OF INSERT AS BEGIN
SET NOCOUNT ON;
-- varchar(10) is to match your table, but probably should be larger
DECLARE @CurrentUser VarChar(10);
SELECT @CurrentUser = SYSTEM_USER;
IF (@CurrentUser NOT IN (SELECT user_name FROM info)) BEGIN
-- consider using an identity column for the key instead of this
INSERT INTO info (userid, user_name)
SELECT
ISNULL((SELECT MAX(userid) FROM info), 0) + 1,
@CurrentUser;
END;
INSERT INTO orders (order_id, quantity, cost, total_cost, created_date, created_by)
SELECT
INS.order_id,
INS.quantity,
INS.cost,
INS.total_cost,
GETDATE(),
@CurrentUser
FROM INSERTED INS;
END;