Advertisement
Guest User

Untitled

a guest
May 22nd, 2018
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 15.49 KB | None | 0 0
  1. create user patron identified by 123; --Crear un usuario dueño de los objetos
  2.  
  3. grant dba,connect,resource to patron; --Otorgar permisos de administración del esquema
  4.  
  5. create tablespace users1 logging datafile 'C:\oraclexe\app\oracle\oradata\users1.dbf'size 1024M; --Crear 3 tablespaces (Usuarios, Tablas, Índices)
  6. create tablespace index1 logging datafile 'C:\oraclexe\app\oracle\oradata\index1.dbf'size 1024M;
  7. create tablespace table1 logging datafile 'C:\oraclexe\app\oracle\oradata\table1.dbf'size 1024M;
  8.  
  9. create user solo_consultas identified by 123 default tablespace users1; --Crear dos usuarios: Consular, Insertar
  10.  
  11. create user solo_insert identified by 123 default tablespace users1;-- Crear usuarios
  12. grant select any table to solo_consultas;--otorgar permisos
  13. grant insert any table to solo_insert;--otorgar permisos
  14. grant create session to solo_consultas;--otorgar permisos
  15. grant create session to solo_insert;--otorgar permisos
  16. --///////////////////////////////////////// C R E A T E T A B L E //////////////////////////////////////////////////////
  17. create table categoria (
  18. codigo_categoria number not null primary key,
  19. nombre_categoria varchar(50)
  20. constraint fk5 add foreign key(nombre_categoria) reference producto(categoria))tablespace table1;
  21. )
  22. producto
  23.  
  24.  
  25. create table cliente(
  26. codigo smallint not null primary key,
  27. ap_paterno varchar(50) not null,
  28. ap_materno varchar(50) not null,
  29. direccion varchar(50) not null,
  30. telefono varchar(50) not null,
  31. clase varchar(50) not null,
  32. num_compras integer not null,
  33. edad smallint not null,
  34. createby varchar(10) not null,
  35. inserttime timestamp not null,
  36. fecha_nacimiento date not null,
  37. credito_ocupado number not null,
  38. credito_disponible number not null,
  39. credito_otorgado number not null)
  40. tablespace table1;
  41.  
  42. create table cargos(
  43. cargo varchar(50) primary key,
  44. salario_max number not null,
  45. salario_min number not null)
  46. tablespace table1;
  47.  
  48. create table empleado(
  49. rut varchar(12) not null primary key,
  50. ap_paterno varchar(50) not null,
  51. direccion varchar(50)NOT NULL,
  52. telefono varchar(50) not null,
  53. cargo varchar(50) not null,
  54. edad smallint not null,
  55. createby varchar(10) not null,
  56. inserttime timestamp not null,
  57. fecha_nacimiento date not null,
  58. salario int not null)
  59. tablespace table1
  60.  
  61. create table producto(
  62. codigo varchar(50) not null primary key,
  63. descripcion varchar(50) not null,
  64. categoria varchar(50) not null,
  65. stock_minimo number not null,
  66. stock_maximo number not null,
  67. precio_actual number not null)
  68. tablespace table1
  69.  
  70. create table pedido(
  71. codigo varchar(50) not null primary key,
  72. cantidad number not null,
  73. fecha date,
  74. codigo_cliente smallint not null,
  75. total_pedido number not null,
  76. estado varchar(50) not null,
  77. fecha_entrega date not null,
  78. rut_empleado varchar(50) not null)
  79. tablespace table1
  80.  
  81. create table detalle_pedido(
  82. id smallint not null,
  83. codigo_producto_id varchar(50) not null,
  84. cantidad number not null,
  85. precio_unitario number not null,
  86. subtotal number not null,
  87. impuestos number not null,
  88. num_linea smallint not null
  89. )tablespace table1;
  90.  
  91. --/////////////////////////////////////////A L T E R T A B L E/////////////////////////////////////////////////////////////////////
  92. alter table empleado add constraint clave_foranea1 foreign key (cargo) references cargos(cargo);
  93. alter table pedido add constraint clave_foranea2 foreign key (codigo_cliente) references cliente(codigo);
  94. alter table pedido add constraint clave_foranea3 foreign key (rut_empleado) references empleado(rut);
  95. alter table detalle_pedido add constraint clave_foranea4 foreign key (codigo_producto_id) references producto(codigo);
  96. alter table cliente add fecha_ultimo_pedido date;
  97. alter table cliente add constraint check_credito check (credito_otorgado >= 0);
  98. alter table empleado add constraint check_rango_salario check(salario >=0);
  99.  
  100. --//////////////////////////////// INSERT CLIENTES///////////////////////////////////
  101. insert into cliente (codigo, ap_paterno, ap_materno, direccion, telefono, clase, num_compras, edad, createby, inserttime,fecha_nacimiento,
  102. credito_ocupado, credito_disponible, credito_otorgado)
  103. values ('1' ,'FARKAS','KLEIN','NEW YORK (EEUU)','11111111','VIP','9','51','DIOS',current_timestamp,'20/03/1967','50','150','200');
  104.  
  105. insert into cliente (codigo, ap_paterno, ap_materno, direccion, telefono, clase, num_compras, edad, createby, inserttime,fecha_nacimiento,
  106. credito_ocupado, credito_disponible, credito_otorgado)
  107. values ('2' ,'VASQUEZ','CAMPOS','CALIFORNIA (EEUU)','22222222','CLIENTE ESPORADICO','2','22','DIOS',current_timestamp,'04/01/1996','10','15','25');
  108.  
  109. insert into cliente (codigo, ap_paterno, ap_materno, direccion, telefono, clase, num_compras, edad, createby, inserttime,fecha_nacimiento,
  110. credito_ocupado, credito_disponible, credito_otorgado)
  111. values ('3' ,'QUINTEROS','ELGUETA','TALCA (CHILE)','33333333','CLIENTE ESPORADICO','0','22','DIOS',current_timestamp,'12/09/1996','10','15','25');
  112.  
  113. --////////////////////////////I N S E R T C A R G O/////////////////////////////////
  114.  
  115. insert into cargos(cargo,salario_max,salario_min)
  116. values ('GERENTE(OPERACIONES)','5000000','2000000');
  117.  
  118. insert into cargos(cargo,salario_max,salario_min)
  119. values ('INGENIERO','2300000','1500000');
  120.  
  121. insert into cargos(cargo,salario_max,salario_min)
  122. values ('OPERADOR','1500000','1000000');
  123.  
  124. insert into cargos(cargo,salario_max,salario_min)
  125. values ('JEFE REGIONAL','7000000','4000000');
  126.  
  127. insert into cargos(cargo,salario_max,salario_min)
  128. values ('GERENTE GENERAL','10000000','8000000');
  129.  
  130.  
  131. --///////////////////////////////// I N S E R T E M P L E A D O/////////////////////////////////////
  132.  
  133.  
  134.  
  135. insert into empleado(rut,ap_paterno,direccion,telefono,cargo,edad,createby,inserttime,fecha_nacimiento,salario)
  136. values ('1111111111-1','PEREZ','P SHERMAN CALLE WALLABY 42 SYDNEY','123456789','INGENIERO','29','DIOS',CURRENT_TIMESTAMP,'21/01/2018','1550000');
  137.  
  138. insert into empleado(rut,ap_paterno,direccion,telefono,cargo,edad,createby,inserttime,fecha_nacimiento,salario)
  139. values ('1111111111-2','LOPEZ','TALCA','123456789','INGENIERO','22','DIOS',CURRENT_TIMESTAMP,'21/01/2018','1250000');
  140.  
  141. insert into empleado(rut,ap_paterno,direccion,telefono,cargo,edad,createby,inserttime,fecha_nacimiento,salario)
  142. values ('1111111111-3','NAVARRETE','SANTIAGO','123456789','INGENIERO','29','DIOS',CURRENT_TIMESTAMP,'21/01/2018','1550000');
  143.  
  144. insert into empleado(rut,ap_paterno,direccion,telefono,cargo,edad,createby,inserttime,fecha_nacimiento,salario)
  145. values ('1111111111-4','VENEGAS','CONCEPCION','123456789','INGENIERO','29','DIOS',CURRENT_TIMESTAMP,'21/01/2018','1550000');
  146.  
  147. insert into empleado(rut,ap_paterno,direccion,telefono,cargo,edad,createby,inserttime,fecha_nacimiento,salario)
  148. values ('1111111111-5','VILLASECA','ANTOFALOMBIA','123456789','GERENTE(OPERACIONES)','23','DIOS',CURRENT_TIMESTAMP,'21/01/2018','4550000');
  149.  
  150. insert into empleado(rut,ap_paterno,direccion,telefono,cargo,edad,createby,inserttime,fecha_nacimiento,salario)
  151. values ('1111111111-6','VASQUEZ','TALCA','123456789','JEFE REGIONAL','29','DIOS',CURRENT_TIMESTAMP,'21/01/2018','9550000');
  152.  
  153. SELECT*FROM empleado
  154.  
  155.  
  156.  
  157. --/////////////////////////////// T E S T E R/////////////
  158. --conn solo_insert contraseña 123
  159.  
  160.  
  161. --////////////////////////////////// INSERT PRODUCTOS/////////////////////////////////////
  162. insert into producto (codigo, descripcion , categoria, stock_minimo, stock_maximo,precio_actual)
  163. values ('111' , 'QUESO DE ELABORACION ARTESANAL', 'LACTEOS','10','100','3990');
  164.  
  165. insert into producto (codigo, descripcion , categoria, stock_minimo, stock_maximo,precio_actual)
  166. values ('112' , 'HELADO DE CHOCOLATE', 'POSTRES','10','100','2590');
  167.  
  168. insert into producto (codigo, descripcion , categoria, stock_minimo, stock_maximo,precio_actual)
  169. values ('113' , 'YOGUR', 'LACTEOS','10','100','390');
  170.  
  171. insert into producto (codigo, descripcion , categoria, stock_minimo, stock_maximo,precio_actual)
  172. values ('114' , 'LECHE ENTERA(1 LITRO)', 'LACTEOS','10','100','790');
  173.  
  174. insert into producto (codigo, descripcion , categoria, stock_minimo, stock_maximo,precio_actual)
  175. values ('115' , 'LENTEJAS (1 KILO)','LEGUMBRES ','10','50','2279');
  176.  
  177. insert into producto (codigo, descripcion , categoria, stock_minimo, stock_maximo,precio_actual)
  178. values ('116' , 'LOMO LISO Cat.V(1 KILO)', 'CARNES','10','60','9490');
  179.  
  180. insert into producto (codigo, descripcion , categoria, stock_minimo, stock_maximo,precio_actual)
  181. values ('117' , 'CARMENERE CASILLERO DEL DIABLO 1.5 LITROS ', 'VINOS','1','25','4529');
  182.  
  183. insert into producto (codigo, descripcion , categoria, stock_minimo, stock_maximo,precio_actual)
  184. values ('118' , 'TORTA MIL HOJAS (15 PORCIONES)', 'PASTELERIA','0','5','12390');
  185.  
  186. insert into producto (codigo, descripcion , categoria, stock_minimo, stock_maximo,precio_actual)
  187. values ('119' , 'CHEESECAKE(UNIDAD)', 'PASTELERIA','0','10','7590');
  188.  
  189. insert into producto (codigo, descripcion, categoria, stock_minimo, stock_maximo, precio_actual)
  190. values ('120' , 'PALTA (HASS 1 KILO)', 'FRUTAS Y VERDURAS' ,'5','15','5000');
  191.  
  192.  
  193. --/////////////////////////I N S E R T P E D I D O////////////////////
  194. INSERT INTO pedido(codigo,cantidad,fecha,codigo_cliente,total_pedido,estado,fecha_entrega,rut_empleado)
  195. values ('0001','2',current_date,'1','250','PENDIENTE','29/05/2018','1111111111-2');
  196.  
  197. delete from pedido
  198. --//////////////////////////////////////////////I N S E R T DETALLE_PEDIDO//////////////////////////
  199. insert into detalle_pedido(id,codigo_producto_id,cantidad,precio_unitario,subtotal,impuestos,num_linea)
  200. values ('11','112','1','2590','2590','4000','321');
  201.  
  202. desc detalle_pedido;
  203. select*from detalle_pedido;
  204. --/////////////////////////////////////////////////F U N C I O N E S///////////////////////////////////////////////////
  205.  
  206. --new y old se usan en los trigger
  207. --los triger se ejecutan sobre tablas
  208.  
  209.  
  210. CREATE OR REPLACE FUNCTION total_pedido(codigo varchar(50))
  211. RETURN NUMBER is
  212.  
  213. total NUMBER;
  214. codigo_pedido VARCHAR;
  215.  
  216. BEGIN
  217. UPDATE pedido SET total_pedido=total_pedido(codigo);
  218. SELECT round (sum(precio*cantidad)*1.19),codigo_pedido into total_pedido,codigo_pedido,
  219. FROM pedido P JOIN detalle_pedido DP on p.codigo_pedido=DP codigo_pedido,
  220. WHERE p.codigo=codigo_producto,
  221. GROUP BY codigo_preducto return total_pedido
  222. END;
  223.  
  224. begin
  225. update pedido SET total_pedido = pedido(codigo);
  226. select
  227.  
  228.  
  229. update pedido set total_pedido = total_pedido(codigo.producto
  230.  
  231.  
  232.  
  233. CREATE OR REPLACE FUNCTION fn_suma_precio_productos
  234. (calculando IN number)
  235. return number
  236. IS
  237. calculo1 number (9);
  238. BEGIN
  239. select sum(precio_actual)
  240. into calculo1
  241. from producto
  242. where precio_actual = calculando;
  243. return calculo1;
  244. END;
  245.  
  246. select descripcion as nombre_del_producto
  247. ,fn_promedio_precio_productos(precio_actual)as
  248. from producto;
  249.  
  250. select sum (p.precio_actual)
  251. from producto p;
  252.  
  253. create view selecciona_todo as select*from producto
  254.  
  255. select *from selecciona_todo
  256. create view sumas as select sum (p.precio_actual) as sumar_algo
  257. from producto p;
  258. select *from sumas
  259. -- ME DA SUMA DE TODOS LOS PRODUCTOS INSERTADOS EN LA TABLA PRODUCTOS
  260. select avg (pr.precio_actual)
  261. from producto pr;
  262.  
  263. select p from p;
  264. select sum (d.subtotal)
  265. from detalle_pedido d join producto p
  266. on d.codigo_preducto_id = p.id
  267.  
  268.  
  269. desc cliente;
  270. select *from producto
  271. SELECT *FROM CLIENTE
  272. delete from producto-- Borra todas las filas de una tabla U S A R C O N C U I D A D O
  273.  
  274.  
  275. --////////////////////////////////////C R E A T E T R I G G E R//////////////////////
  276.  
  277. --caso de uso para el informe (crear un pedido) ejecutar todas las cosas , todos los trigger,todas las funcines,consultas etc
  278. --SALARIO POR CARGO
  279. create or replace trigger rango_salario
  280. before insert on empleado
  281. for each row
  282. declare
  283. raise_fuera_rango exception;
  284. min_salario number;
  285. max_salario number;
  286. begin
  287. select salario_max, salario_min into max_salario, min_salario from cargos where cargo=:NEW.cargo;
  288. if(:NEW.salario<min_salario or :NEW.salario>max_salario) then
  289. raise raise_fuera_rango;
  290. end if;
  291. exception
  292. when raise_fuera_rango then
  293. raise_application_error(-20300,'El salario esta fuera de rango');
  294. end;
  295.  
  296. select*from empleado
  297. -- Verificar si el pedido se puede hacer si tiene crédito disponible
  298.  
  299. CREATE OR REPLACE TRIGGER verifica_pedido
  300. before insert on pedido
  301. for each row
  302. declare
  303. credit_dispo number;
  304. total_ped number;
  305. raise_credito_insufuciente exception;
  306. begin
  307. select credito_disponible into credito_disponible from cliente where pedido =:NEW.total_pedido;
  308. if(:NEW.total_pedido>credito_disponible or :NEW.credito_disponible <1) then --Con credito == 1 nadie puede comprar nada
  309. raise raise_credito_insuficiente;
  310. end if;
  311. exception
  312. when raise_credito_insuficiente then
  313. raise_application_error(-20301,'No se puede realizar su pedido (Credito Insuficiente');
  314. end;
  315.  
  316. -- VENTA DE ALCOHOL A MENORES
  317.  
  318.  
  319.  
  320. create or replace trigger venta_alcohol
  321. before insert on pedido
  322. for each row
  323. declare
  324. raise_edad_no_permitida exception;
  325. cliente_edad number;
  326. begin
  327. select edad into cliente_edad from cliente where cargo=:NEW.cargo;
  328. if(:NEW.edad<18 ) then
  329. raise raise_edad_no_permitida;
  330. end if;
  331. exception
  332. when raise_edad_no_permitida then
  333. raise_application_error(-20300,'MENOR DE EDAD DETECTED LLAMANDO A LA PDI');
  334. end;
  335.  
  336. create or replace trigger licores_mayores_18
  337. before insert on pedido
  338. for each row
  339.  
  340. declare
  341. edad_excedida exception;
  342.  
  343. begin
  344. select edad from cliente where cliente.codigo=pedido.codigo_cliente;
  345. if(:new.edad<17) then
  346. raise edad_excedida;
  347. end if;
  348. exception
  349. when edad_excedida then
  350. raise_application_error(-20310,'El cliente debe ser mayor de 18 para comprar licores');
  351. end;
  352.  
  353. select c.credito_disponible
  354. from cliente c join pedido p
  355. on p.codigo_cliente=c.codigo
  356.  
  357.  
  358.  
  359. select*from pedido
  360. select*from cliente
  361. delete from pedido
  362.  
  363.  
  364. --/////////////////////////////////////D A N G E R C U I D A D O /////////////////////////////////////////////////
  365.  
  366. create or replace TRIGGER TGR_detalle_pedido_subtotal
  367. BEFORE INSERT ON detalle_pedido_aux
  368. FOR EACH ROW
  369. DECLARE
  370. num_lineas SMALLINT;
  371. sub_total NUMBER;
  372. stock_t numbeR;
  373. cliente_t smallint;
  374. credito_t number;
  375. raise_no_credito exception;
  376. BEGIN
  377.  
  378. select count() into num_lineas from detalle_pedido where (detalle_pedido.codigo_pedido=:new.codigo_pedido);
  379. sub_total:=(:new.cantidad:new.precio_unitario)-(:new.cantidad:new.precio_unitario:new.impuestos);
  380. insert into detalle_pedido(id,CODIGO_PRODUCTO_ID,cantidad,PRECIO_UNITARIO,SUBTOTAL,IMPUESTOS,NUM_LINEA,CODIGO_PEDIDO) values(:new.id,:new.codigo_producto_id,:new.cantidad,:new.precio_unitario,sub_total,:new.impuestos,num_lineas,:new.codigo_pedido);
  381.  
  382. select codigo_cliente into cliente_t from pedido where pedido.codigo=:new.codigo_pedido;
  383. select credito_disponible into credito_t from cliente where codigo=cliente_t;
  384. if(sub_total<credito_t) then
  385. update CLIENTE set credito_disponible=(credito_disponible-sub_total) where cliente.codigo=cliente_t;
  386. update cliente set credito_ocupado=(credito_otorgado-credito_disponible) where cliente.codigo=cliente_t;
  387. update pedido set total_pedido=pedido.total_pedido+sub_total where pedido.codigo=:new.codigo_pedido;
  388.  
  389. select stock_actual into stock_t from pedido.producto where pedido.producto.codigo=:NEW.codigo_producto_id;
  390. update PRODUCTO set STOCK_ACTUAL=(stock_t-:new.cantidad) where PRODUCTO.CODIGO=:new.codigo_producto_id;
  391. else
  392. raise raise_no_credito;
  393. end if;
  394. exception
  395. when raise_no_credito then
  396. raise_application_error(-20300,'No hay credito suficiente');
  397. END;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement