Sql Oracle DBMS插入过程不工作
我正在为我的数据库开发一个简单的功能 当用户注册我的应用程序时,一个字段Sql Oracle DBMS插入过程不工作,sql,oracle,stored-procedures,Sql,Oracle,Stored Procedures,我正在为我的数据库开发一个简单的功能 当用户注册我的应用程序时,一个字段password\u changed被初始化为0,在我的user trigger中执行此操作时,我想启动以下方法向新用户发送一条消息,告诉他们应该更新密码 CREATE OR REPLACE TRIGGER trg_users BEFORE INSERT OR UPDATE ON users FOR EACH ROW BEGIN -- Get the new user id IF :NEW.user_id I
password\u changed
被初始化为0,在我的user trigger
中执行此操作时,我想启动以下方法向新用户发送一条消息,告诉他们应该更新密码
CREATE OR REPLACE TRIGGER trg_users
BEFORE INSERT OR UPDATE ON users FOR EACH ROW
BEGIN
-- Get the new user id
IF :NEW.user_id IS NULL THEN
SELECT seq_user_id.nextval
INTO :NEW.user_id
FROM sys.dual;
END IF;
-- Alert a user that they need to change their password
IF :NEW.pass_changed IS NULL THEN
:NEW.pass_changed := 0;
send_alert(:NEW.user_id, 'Thank-you for registering, please change your password for security reasons!');
END IF;
END;
第一个触发器只是初始化设置为0
的密码,然后调用我的send\u alert()函数,获取由我的序列填充的:NEW.user\u id
发送警报()过程:
-- Sends an alert to the user noting that they haven't changed their password
CREATE OR REPLACE PROCEDURE send_alert(
this_user users.user_id%TYPE,
this_message STRING
)
AS
BEGIN
INSERT INTO messages
VALUES('', this_user, getSystemId(), 'ALERT', this_message, '', '');
END send_alert;
当此代码运行时,我发现错误完整性约束(PRCSE.INBOX\u MESSAGE\u TO\u FK)被违反-未找到父密钥
我理解这意味着什么-但是父密钥的值应通过此用户
填充,如果我将该字段替换为现有值,则过程将完成,并为旧用户插入
我只能认为由于某种原因,:NEW.user_id
没有被传递,但是我在调用我的过程之前初始化了它的值
编辑2014年4月10日13:48 GMT:要清除任何混淆,getSystem()返回主管理员id
-- Gets the ID of the SYSTEM user via its unique email
CREATE OR REPLACE FUNCTION getSystemId
RETURN NUMBER
IS
system_user users.user_id%TYPE;
pragma autonomous_transaction;
BEGIN
SELECT user_id
INTO system_user
FROM users
WHERE user_email = 'system@application.com'
AND user_permissions = 'ADMIN';
RETURN system_user;
COMMIT;
END getSystemId;
如有任何帮助,将不胜感激:
尊敬的Alex。这是因为您试图在触发器之前(例如,在插入父行之前)插入值:
插入后的触发器如何?@OracleUser这确实是解决方案-我是Oracle DB的新手,很高兴我现在能看到这个特定场景是如何解决的-谢谢!)啊,我觉得太傻了-我真不敢相信我没有发现,澄清一下,before触发器在执行插入之前准备了所有的值,所以即使:NEW.user_id已经增加,但它在表中还不存在,因此违反了键?谢谢你的帮助,顺便说一句:)是的,顺便说一句,如果你真的需要这种逻辑,你可以使用延迟约束-它不会立即出现大小写异常,而是等待检查,直到提交。但它也有一些缺点,比如性能差。有趣的是,我可能会读到这一点-再次感谢您的帮助。
SQL> create table t(x int primary key);
SQL> create table t_c(x int references t(x));
SQL> create or replace trigger tr_i
2 before insert on t
3 for each row
4 begin
5 insert into t_c(x) values(:new.x);
6 end;
7 /
SQL> insert into t values(1);
insert into t values(1)
*
error in line 1:
ORA-02291: integrity constraint (SCOTT.SYS_C00330529) voilated - parent key not found
ORA-06512: in "SCOTT.TR_I", line 2
ORA-04088: error in trigger execution 'SCOTT.TR_I'
SQL> create or replace trigger tr_i
2 after insert on t
3 for each row
4 begin
5 insert into t_c(x) values(:new.x);
6 end;
7 /
SQL> insert into t values(1);
1 row inserted.
SQL> select * from t;
X
------
1
SQL> select * from t_c;
X
------
1