oracle 自增长、触发器、函数

oracle 跟mysql 实现 主键自增长的方式不一样

实现自增

create table student(id number,name VARCHAR2(32),primary key(id));

select * from student;

create sequence student_seq minvalue 1 nomaxvalue
increment by 1 start with 1 nocache;

select student_seq.nextval from dual;

create or replace trigger student_trigger_insertid
before insert on student for each row
begin
	select student_seq.nextval into:new.id from dual;
end;


insert into student(name) values('zhangsan');

通过触发器 将序列的自增插入到表中 实现表的自增

在这里插入图片描述
触发器

create or replace trigger tr_stu
 before delete on student
 begin
	if user != 'LIHUA' then
			raise_application_error(-20001,'权限不足,只能是LIHUA用户');
	end if;
	end;
	
	select * from student;
	
	delete from student where id=2;

上面的触发器的意思是 LIHUA 用户才能对表student有删除权限

在这里插入图片描述
切换用户LIHUA
执行语句成功

delete from student where id=2;

在这里插入图片描述

函数

	create or replace function test_function return number as
	begin
		declare total_count number;
		begin
			select count(*) into total_count from student ;
			return total_count;
		end;
	end;
		
	
select test_function() as num from dual;

在这里插入图片描述
函数传参
切换到scott
在这里插入图片描述

	create or replace function emp_function(ss number) return VARCHAR2 as
	begin
		declare emp_count number;
		begin
			select count(*) into emp_count from SCOTT.emp where sal>= +ss;
			if emp_count>0 then
			dbms_output.put_line('有'|| emp_count || '名员工薪资大于'|| ss);
			return '有'|| emp_count || '名员工薪资大于'|| ss;
			else if emp_count<=0 then
			dbms_output.put_line('没有员工薪资大于' || ss);
			return '没有员工薪资大于' || ss;
			end if;
			end if;
		end;
	end;
	
	select emp_function(2000) from dual;

在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值