Code SQL Flashcards
Create tablespace
CREATE TABLESPACE TBS1
DATAFILE ‘C’
SIZE n m
AUTOEXTEND ON
MAXSIZE UNLIMITED;
Delete Tablespace
DROP TABLESPACE TBS1INCLUDING CONTENTS AND DATAFILES;
Change default tablespace
ALTER USER HR DEFAULT TABLESPACE TBS1;
Create table in tablespace
CREATE TABLE HR.TAB1(id NUMBER(30));
Insert multiple entries into Table with 1 Column
INSERT INTO HR.TAB1
SELECT level FROM dual
CONNECT BY level <= 100000;
Create table with 2 columns
CREATE TABLE HR.TAB2(id NUMBER(30), name VARCHAR2(50));
Insert multiple entries into table with 2 columns
INSERT INTO HR.TAB2(id, name)
SELECT level, ‘Name’ ||level – || for string concat
FROM dual
CONNECT BZ level <= 100;
Create table with constrains
CREATE TABLE HR.TAB1
(user_id NUMBER (30) CONSTRAINT PK_USER_ID PRIMARY KEY,
user_name VARCHAR(300 CHAR) CONSTRAINT NN_USER_NAME NOT NULL,
create_date DATE CONSTRAINT NN_CREATE_DATE NOT NULL,
CONSTRAINT fk_student_id FOREIGN KEY (sid) REFERENCES UNI.student (sid));
User Anlegen
CREATE USER UNI IDENTIFIED BY uni;
GRANTS
GRANT CREATE SEESION TO UNI;
GRANT CREATE TABLE TO UNI;
GRANT SELECT ON HR.HR_TAB4 TO UNI;
Insert Value into Table
INSERT INTO table(sid, name, create_date)
VALUES(1,’durra’,SYSTIMESTAMP,TO_DATE(‘2023-06-30));
Package Header
– Create a package header
CREATE OR REPLACE PACKAGE circle_area_pkg IS
– Package Specification
FUNCTION calculate_area(radius NUMBER) RETURN NUMBER;
END circle_area_pkg;
Create Package Body
CREATE OR REPLACE PACKAGE BODY circle_area_pkg IS
– Package Body
FUNCTION calculate_area(radius NUMBER) RETURN NUMBER IS
pi CONSTANT NUMBER := 3.14159;
BEGIN
RETURN pi * radius * radius;
END calculate_area;
END circle_area_pkg;
Call Function in Package
– Call the calculate_area function from the package
DECLARE
radius NUMBER := 5;
area NUMBER;
BEGIN
area := circle_area_pkg.calculate_area(radius);
DBMS_OUTPUT.PUT_LINE(‘Area: ‘ || area);
END;
Create and edit Sequence
– sequence stuff
CREATE SEQUENCE my_seq
START WITH 1
INCREMENT BY 1
NOMAXVALUE;
ALTER SEQUENCE my_seq
INCREMENT BY 2;
SELECT my_seq.NEXTVAL FROM DUAL;
– enable dbms output
SET SERVEROUTPUT ON;
– PL/SQL Block
DECLARE – Declare Variables, allocate memory for cursors and define data types
currval_seq NUMBER;
BEGIN – Execute SQL Code and/or Statements -> After Begin there can be implemented an exception block for exceptions
SELECT my_seq.CURRVAL – can just be accessed after calling NEXTVAL at least once!
INTO currval_seq
FROM DUAL;
DBMS_OUTPUT.PUT_LINE(currval_seq); DBMS_OUTPUT.PUT_LINE(my_seq.NEXTVAL); END;