Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Database Management Systems Lab. Solutions

2,894 views

Published on

Database Management Systems Lab. Solutions

Published in: Engineering
  • Easy and hassle free way to make money online! I have just registered with this site and straight away I was making money! It doesn't get any better than this. Thank you for taking out all the hassle and making money answering surveys as easy as possible even for non-techie guys like me!  http://ishbv.com/goldops777/pdf
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • D0WNL0AD FULL ▶ ▶ ▶ ▶ http://1lite.top/MT6nS ◀ ◀ ◀ ◀
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • Try this before jerking off. Just send a message and ask to F.U.C.K... ★★★ http://t.cn/AiuWSRdj
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • GIVE HER A BIGGER PACKAGE THIS VALENTINE'S DAY ●●● http://t.cn/Ai88iYkP
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • Do This Simple 2-Minute Ritual To Loss 1 Pound Of Belly Fat Every 72 Hours ▲▲▲ https://tinyurl.com/bkfitness4u
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here

Database Management Systems Lab. Solutions

  1. 1. EXPERIMENT -1 REPORT of DATABASE MANAGEMENT SYSTEMS LAB. LAB GROUP 18 Written by AHMET ÖZDEMİR SOLUTIONS TASK-1 E/R Diagram of problem: manage employees department ha s child works Bu aşamada E/R diyagramının oluşturulmasını ve visual programının nasıl kullanıldığını öğrendik ve alıştırmalar yaptık. ssn salary name age budget dName phone dNo Bu diyagramda child, employee ve department birer entity ve bu entitylere bağlı olan oval kutucuklardaki bilgilerse sahip oldukları belirteçlerdir. Manage, works ve has ise relation olup entitlerin birbirleriyle olan ilişkileri belirtir. Her employees bir veya birden fazla departmanda çalışabilir, her departmanda bir veya birden fazla employee çalışabilir. Ayrıca her employee bir veya daha fazla departmanı yönetebilir, ama her departmanı sadece bir employee yönetebilir. Weak entity olarak tanımladığımız child ise olması zorunlu olmayan varlıktır. Her employeenin bir veya daha fazla çocuğu olabilir ya da hiç olmayabilir; her çocuğunsa sadece bir ebeveyni çalışan olabilir. primary key of employees: ssn primary key of department: dNo primary key of child:name
  2. 2. TASK-2 Create Database and Tables: create database store; use store; create table employees (ssn int primary key, salary money, phone int); create table department (dNo int primary key,dName varchar(20),budget money); create table child (name varchar(50), age int, ssn int NOT NULL, primary key(ssn,name), foreign key(ssn) references employees); create table dep_man (ssn int NOT NULL, dNo int, dName varchar(20),budget money, primary key (dNo), foreign key (ssn) references employees); create table work_in (ssn int, dNo int, dName varchar(20), primary key(ssn,dNo), foreign key (dNo) references department, foreign key (ssn) references employees);
  3. 3. DATABASE MANAGEMENT SYSTEMS 2013-2014 SPRING SEMESTER Creating Tables The create table statement is used to create a new table. Here is the format of a simple create table statement: create table "tablename" ("column1" "data type", "column2" "data type", "column3" "data type"); Format of create table if you were to use optional constraints: create table "tablename" ("column1" "data type" [constraint], "column2" "data type" [constraint], "column3" "data type" [constraint]); [ ] = optional Example: create table employee (first varchar(15), last varchar(20), age number(3), address varchar(30), city varchar(20), state varchar(20)); Inserting into a Table The insert statement is used to insert or add a row of data into the table. To insert records into a table, enter the key words insert into followed by the table name, followed by an open parenthesis, followed by a list of column names separated by commas, followed by a closing parenthesis, followed by the keyword values, followed by the list of values enclosed in parenthesis. The values that you enter will be held in the rows and they will match up with the column names that you specify. Strings should be enclosed in single quotes, and numbers should not. insert into "tablename" (first_column,...last_column) values (first_value,...last_value); In the example below, the column name first will match up with the value 'Luke', and the column name state will match up with the value 'Georgia'.
  4. 4. Example: insert into employee (first, last, age, address, city, state) values ('Luke', 'Duke', 45, '2130 Boars Nest', 'Hazard Co', 'Georgia'); SELECT Statement The select statement is used to query the database and retrieve selected data that match the criteria that you specify. Here is the format of a simple select statement: select "column1" [,"column2",etc] from "tablename" [where "condition"]; [] = optional The column names that follow the select keyword determine which columns will be returned in the results. You can select as many column names that you'd like, or you can use a "*" to select all columns. The table name that follows the keyword from specifies the table that will be queried to retrieve the desired results. The where clause (optional) specifies which data values or rows will be returned or displayed, based on the criteria described after the keyword where. Comparison Operators: The LIKE pattern matching operator can also be used in the conditional selection of the where clause. Like is a very powerful operator that allows you to select only rows that are "like" what you specify. The percent sign "%" can be used as a wild card to match any possible character that might appear before or after the characters specified. For example: select first, last, city from empinfo where first LIKE 'Er%'; This SQL statement will match any first names that start with 'Er'. Strings must be in single quotes.
  5. 5. Experiment 2 1. Create the table that given below and insert the records inside the table. 2. Enter select statements to: a) Display the first name and age for everyone that's in the table. b) Display the first name, last name, and city for everyone that's not from Payson. c) Display all columns for everyone that is over 40 years old. d) Display the first and last names for everyone whose last name ends in an "ay". e) Display all columns for everyone whose first name equals "Mary". f) Display all columns for everyone whose first name contains "Mary".
  6. 6. EXPERIMENT -2 REPORT of DATABASE MANAGEMENT SYSTEMS LAB. LAB GROUP 18 Written by AHMET ÖZDEMİR SOLUTIONS Bu haftaki laboratuvar föyünde bizlere komutlar ile nasıl database oluşturacağımız ve oluşturulan bu database içinde nasıl tablo oluşturacağımız anlatıldı. Ayrıca bu tablolara veri girişinin ve veri görüntülemenin komutlarıda ayrıntılı olarak verildi. Alıştırmalar yaptırarak kendimizi bu konularda pratik kazanmaya yönlendirdi. Bu araştırmalar sırasında LIKE komutunun % işareti ile alakasını içerme olarak kavradık. Bu sayede öğrendiğimiz bilgilerle aşağıdaki komutları yazabildik. EXPERIMENT-2 -Aşağıdaki komut satırı ile lab_2 adında bir database oluşturduk: create database lab_2; -Daha sonra database’de aşağıdaki komutlar ile verilen bilgilere göre bir tablo oluşturduk: use lab_2; create table empinfo (fisrt varchar(20),last varchar(20),id int primary key, age int, city varchar(20),state varchar(20); -Daha sonra oluşturduğumuz bu tabloyu verilen bilgilerle doldurduk: use lab_2; insert into empinfo (first,last,id,age,city,state) values ('John','Janes',99980,45,'Payson','Arizona'); insert into empinfo (first,last,id,age,city,state) values ('Eric','Edwards',88232,32,'San Diego','California'); insert into empinfo (first,last,id,age,city,state) values ('Mary Ann','Edwards',88233,32,'Phoenix','Arizona'); insert into empinfo (first,last,id,age,city,state) values ('Ginger','Howell',98002,42,'Cottonwood','Arizona'); insert into empinfo (first,last,id,age,city,state) values ('Sebastian','Smith',92001,23,'Gila Bend','Arizona'); insert into empinfo (first,last,id,age,city,state) values ('Gus','Gray',22322,35,'Bagdad','Arizona'); insert into empinfo (first,last,id,age,city,state) values ('Mary Ann','May',32326,52,'Tucson','Arizona');
  7. 7. insert into empinfo (first,last,id,age,city,state) values ('Erica','Williams',32327,60,'Show Low','Arizona'); insert into empinfo (first,last,id,age,city,state) values ('Leroy','Brown',32380,22,'Pinetop','Arizona'); insert into empinfo (first,last,id,age,city,state) values ('Elroy','Cleaver',32382,22,'Globe','Arizona'); -Artık tablomuz hazır: Verilen sorulara aşağıdaki kodlar ile yanıt verdik: 1. use lab_2; select first, age from empinfo;
  8. 8. 2. use lab_2; select first,last,city from empinfo where city<> 'Payson'; 3. use lab_2; select * from empinfo where age>=40; 4. use lab_2; select first, last from empinfo where last like '%ay'; 5. use lab_2; select * from empinfo where first like 'Mary'; 6. use lab_2; select * from empinfo where first like '%Mary%';
  9. 9. DATABASE MANAGEMENT SYSTEMS 2013-2014 SPRING SEMESTER Aggregate Functions Aggregate functions are used to compute against a "returned column of numeric data" from your SELECT statement. They basically summarize the results of a particular column of selected data. We are covering these here since they are required by the next topic, "GROUP BY". Although they are required for the "GROUP BY" clause, these functions can be used without the "GROUP BY" clause. For example: SELECT AVG(salary) FROM employee; This statement will return a single result which contains the average value of everything returned in the salary column from the employee table. Example: SELECT Count(*) FROM employees; This particular statement is slightly different from the other aggregate functions since there isn't a column supplied to the count function. This statement will return the number of rows in the employees table. GROUP BY clause The GROUP BY clause will gather all of the rows together that contain data in the specified column(s) and will allow aggregate functions to be performed on the one or more columns. This can best be explained by an example: GROUP BY clause syntax: SELECT column1, SUM (column2) FROM "list-of-tables" GROUP BY "column-list"; Let's say you would like to retrieve a list of the highest paid salaries in each dept:
  10. 10. SELECT max(salary), dept FROM employee GROUP BY dept; This statement will select the maximum salary for the people in each unique department. Basically, the salary for the person who makes the most in each department will be displayed. Their salary and their department will be returned. HAVING clause The HAVING clause allows you to specify conditions on the rows for each group - in other words, which rows should be selected will be based on the conditions you specify. The HAVING clause should follow the GROUP BY clause if you are going to use it. HAVING clause syntax: SELECT column1, SUM(column2) FROM "list-of-tables" GROUP BY "column-list" HAVING "condition"; HAVING can best be described by example. Let's say you have an employee table containing the employee's name, department, salary, and age. If you would like to select the average salary for each employee in each department, you could enter: SELECT dept, avg (salary) FROM employee GROUP BY dept; But, let's say that you want to ONLY calculate & display the average if their salary is over 20000: SELECT dept, avg (salary) FROM employee GROUP BY dept HAVING avg(salary) > 20000;
  11. 11. Experiment 3 1. Create the tables that given below and insert the records inside the table. 2. Select the maximum price of any item ordered in the items_ordered table. 3. Select the average price of all of the items ordered that were purchased in the month of Dec. 4. What is the total number of rows in the items_ordered table? 5. For all of the tents that were ordered in the items_ordered table, what is the price of the lowest tent?
  12. 12. 6. How many people are in each unique state in the customers table? Select the state and display the number of people in each. 7. From the items_ordered table, select the item, maximum price, and minimum price for each specific item in the table. 8. How many orders did each customer make? Use the items_ordered table. Select the customerid, number of orders they made, and the sum of their orders. 9. How many people are in each unique state in the customers table that have more than one person in the state? Select the state and display the number of how many people are in each if it's greater than 1. 10. From the items_ordered table, select the item, maximum price, and minimum price for each specific item in the table. Only display the results if the maximum price for one of the items is greater than 190.00. 11. How many orders did each customer make? Use the items_ordered table. Select the customerid, number of orders they made, and the sum of their orders if they purchased more than 1 item.
  13. 13. EXPERIMENT -3 REPORT of DATABASE MANAGEMENT SYSTEMS LAB. LAB GROUP 18 Written by AHMET ÖZDEMİR SOLUTIONS Bu haftaki laboratuvar föyünde bizlere select komutuyla kullanılan bazı komutlar öğretildi. Bu komutlardan aggregate functions’lar ile tablonun belli bir sütunuyla ilgili yapabileceğimiz karşılaştırma ve sayma komutlarını, group by clause yapısıyla yapılan karşılaştırma ve sayma işlemlerinin sonuçlarını birden fazla veri ile nasıl tabloya aktarılacağını, having clause yapısıyla da yapılan karşılaştırma ve sayma işlemlerine nasıl koşul koyabileceğimizi öğrendik. Föydeki alıştırma ile de öğrendiğimiz bu bilgileri pekiştirmekle birlikte önceki haftaların konularını da tekrar etme imkanı bulduk. EXPERIMENT-3 1* -Aşağıdaki komut satırı ile lab_3 adında bir database oluşturduk: create database lab_3; -Daha sonra database’de aşağıdaki komutlar ile verilen bilgilere göre customers ve items_ordered tablolarını oluşturduk: use lab_3; create table customers (customerid int primary key, firstname varchar(20), lastname varchar(30),city varchar(30),state varchar(30)); *************************************************************************************** use lab_3; insert into customers (customerid,firstname, lastname,city,state) values (10101,'John','Gray','Lynden','Washington'); insert into customers (customerid,firstname, lastname,city,state) values (10298,'Leroy','Brown','Pinetop','Washington'); insert into customers (customerid,firstname, lastname,city,state) values (10299,'Elroy','Keller','Snoqualmie','Washington'); insert into customers (customerid,firstname, lastname,city,state) values (10315,'Lisa','Jones','Oshkosh','Wisconsin'); insert into customers (customerid,firstname, lastname,city,state) values (10325,'Ginger','Schultz','Pocatello','Idaho'); insert into customers(customerid,firstname, lastname,city,state) values (10329,'Kelly','Mendoza','Kailua','Hawaii'); insert into customers (customerid,firstname, lastname,city,state) values (10330,'Shawn','Dalton','Cannon Beach','Oregon'); insert into customers (customerid,firstname, lastname,city,state) values (10338,'Michael','Howell','Tillamook','Oregon'); insert into customers (customerid,firstname, lastname,city,state)
  14. 14. values (10339,'Anthony','Sanchez','Winslow','Arizona'); insert into customers (customerid,firstname, lastname,city,state) values (10408,'Elroy','Cleaver','Globe','Arizona'); insert into customers (customerid,firstname, lastname,city,state) values (10410,'Mary Ann','Howell','Charleston','South Carolina'); insert into customers (customerid,firstname, lastname,city,state) values (10413,'Donald','Davids','Gila Bend','Arizona'); insert into customers (customerid,firstname, lastname,city,state) values (10419,'Linda','Sakahara','Nogales','Arizona'); insert into customers (customerid,firstname, lastname,city,state) values (10429,'Sarah','Graham','Greensboro','North Carolina'); insert into customers (customerid,firstname, lastname,city,state) values (10438,'Kevin','Smith','Durango','Colorado'); insert into customers (customerid,firstname, lastname,city,state) values (10439,'Conrad','Giles','Telluride','Colorado'); insert into customers (customerid,firstname, lastname,city,state) values (10449,'Isabela','Moore','Yuma','Arizona'); ************************************************************************************** use lab_3; select * from customers; *************************************************************************************** use lab_3; create table items_ordered (customerid int not null, order_date date,item varchar(20),quantity int,price money, foreign key(customerid) references customers ); *************************************************************************************** use lab_3; insert into items_ordered (customerid,order_date,item,quantity,price) values (10330,'30-Jun-1999','Pogo stick',1,28); insert into items_ordered (customerid,order_date,item,quantity,price) values (10101,'30-Jun-1999','Raft',1,58);
  15. 15. insert into items_ordered (customerid,order_date,item,quantity,price) values (10298,'01-Jul-1999','Skateboard',1,33); insert into items_ordered (customerid,order_date,item,quantity,price) values (10101,'01-Jul-1999','Life Vest',4,125); insert into items_ordered (customerid,order_date,item,quantity,price) values (10299,'06-Jul-1999','Parachute',1,1250); insert into items_ordered (customerid,order_date,item,quantity,price) values (10339,'27-Jul-1999','Umbrella',1,4.5); insert into items_ordered (customerid,order_date,item,quantity,price) values (10449,'13-Aug-1999','Unicycle',1,180.79); insert into items_ordered (customerid,order_date,item,quantity,price) values (10439,'14-Aug-1999','Ski Poles',2,25.5); insert into items_ordered (customerid,order_date,item,quantity,price) values (10101,'18-Aug-1999','Rain Coat',1,18.3); insert into items_ordered (customerid,order_date,item,quantity,price) values (10449,'01-Sep-1999','Snow Shoes',1,45); insert into items_ordered (customerid,order_date,item,quantity,price) values (10439,'18-Sep-1999','Tent',1,88); insert into items_ordered (customerid,order_date,item,quantity,price) values (10298,'19-Sep-1999','Lantern',2,29); insert into items_ordered (customerid,order_date,item,quantity,price) values (10410,'28-Oct-1999','Sleeping Bag',1,89.22); insert into items_ordered (customerid,order_date,item,quantity,price) values (10438,'01-Nov-1999','Umbrella',1,6.75); insert into items_ordered (customerid,order_date,item,quantity,price) values (10438,'02-Nov-1999','Pillow',1,8.5); insert into items_ordered (customerid,order_date,item,quantity,price) values (10298,'01-Dec-1999','Helmet',1,22); insert into items_ordered (customerid,order_date,item,quantity,price) values (10449,'15-Dec-1999','Bicycle',1,380.5); insert into items_ordered (customerid,order_date,item,quantity,price) values (10449,'22-Dec-1999','Canoe',1,280); insert into items_ordered (customerid,order_date,item,quantity,price) values (10101,'30-Dec-1999','Hoola Hoop',3,1.75); insert into items_ordered (customerid,order_date,item,quantity,price) values (10330,'01-Jan-1999','Flashlight',4,28); **************************************************************************************** use lab_3; select * from items_ordered;
  16. 16. -Tablolarımızı ouşturduktan sonra öğrendiğimiz yapıları kullanarak soruları yanıtladık: 2* -items_ordered tablosundaki maksimum price’ı veren komut: use lab_3; select max(price) from items_ordered; 3* -items_ordered tablosundaki 12. ayda yapılan sipariş tutarının ortalaması: use lab_3; select avg(price) from items_ordered where order_date like'%-12-%'; 4* -items_ordered tablosundaki toplam satır sayısı: use lab_3; select count(*) from items_ordered;
  17. 17. 5* -items_ordered tablosundaki tent ürün siparişinin minimum fiyatlısı: use lab_3; select min(price) from items_ordered where item like 'tent'; 6* -customers tablosundaki her bir şehrin kaç kere kullanıldığı: use lab_3; select state, count(state) from customers group by state; 7* -items_ordered tablosundaki her bir ürünün maksimum ve minimum sipariş fiyatını verir: use lab_3; select item, max(price),min(price) from items_ordered group by item;
  18. 18. 8* -items_ordered tablosundaki her bir customerin yaptığı siparişi sayar ve yapılan siparişlerin toplam tutarını verir: use lab_3; select customerid, count(customerid),sum(price) from items_ordered group by customerid; 9* -customers tablosundaki her bir statede yaşayan sayısı birden fazla olanları sayar : use lab_3; select state, count(customerid) from customers group by state having count(customerid)>1;
  19. 19. 10* -items_ordered tablosundaki her bir itemin maksimum ve minimum tutardaki değerini 190’dan fazla olmak koşuluyla gösterir: use lab_3; select item, max(price),min(price) from items_ordered group by item having max(price)>190; 11* -items_ordered tablosundaki her bir müşterinin verdiği sipariş sayısının birden fazla olması koşuluyla toplam sipariş tutarını verir: use lab_3; select customerid, count(customerid),sum(price) from items_ordered group by customerid having count(customerid)>1;
  20. 20. DATABASE MANAGEMENT SYSTEMS 2013-2014 SPRING SEMESTER IN & BETWEEN SELECT col1, SUM(col2) FROM "list-of-tables" WHERE col3 IN (list-of-values); SELECT col1, SUM(col2) FROM "list-of-tables" WHERE col3 BETWEEN value1 AND value2; The IN conditional operator is really a set membership test operator. That is, it is used to test whether or not a value (stated before the keyword IN) is "in" the list of values provided after the keyword IN. For example: SELECT employeeid, lastname, salary FROM employee_info WHERE lastname IN ('Hernandez', 'Jones', 'Roberts', 'Ruiz'); This statement will select the employeeid, lastname, salary from the employee_info table where the lastname is equal to either: Hernandez, Jones, Roberts, or Ruiz. It will return the rows if it is ANY of these values. The IN conditional operator can be rewritten by using compound conditions using the equals operator and combining it with OR - with exact same output results: SELECT employeeid, lastname, salary FROM employee_info WHERE lastname = 'Hernandez' OR lastname = 'Jones' OR lastname = 'Roberts' OR lastname = 'Ruiz'; As you can see, the IN operator is much shorter and easier to read when you are testing for more than two or three values. You can also use NOT IN to exclude the rows in your list. The BETWEEN conditional operator is used to test to see whether or not a value (stated before the keyword BETWEEN) is "between" the two values stated after the keyword BETWEEN. For example: SELECT employeeid, age, lastname, salary FROM employee_info WHERE age BETWEEN 30 AND 40; This statement will select the employeeid, age, lastname, and salary from the employee_info table where the age is between 30 and 40 (including 30 and 40).
  21. 21. This statement can also be rewritten without the BETWEEN operator: SELECT employeeid, age, lastname, salary FROM employee_info WHERE age >= 30 AND age <= 40; You can also use NOT BETWEEN to exclude the values between your range. Experiment 4 Figure 1. Relational Schema 1) Create the tables that given in figure 1. 2) Insert the records that given below. Departments 14, IT, 65000 37, Accounting, 15000 59, Human Resources, 240000 77, Research, 55000 Employees 123234877, Michael , Rogers, 14 152934485, Anand, Manikutty, 14 222364883, Carol, Smith, 37 326587417, Joe, Stevens, 37 332154719, Mary-Anne, Foster, 14 332569843, George , Odonnel , 77 546523478, John , Doe, 59 631231482, David, Smith, 77 654873219, Zacary, Efron, 59 745685214, Eric, Goldsmith, 59 845657245, Elizabeth, Doe , 14 845657246, Kumar, Swamy, 14 3) Answer the queries that given below.  Select the last name of all employees, without duplicates.  Select all the data of employees whose last name is "Smith" or "Doe". Hint: Use ‘IN’ syntax to answer this query.  Select all the data of employees that work in department 37 or department 77. Hint: Use ‘IN’ syntax to answer this query.  Select all the data of employees whose last name begins with an "S".  Select the sum of all the departments' budgets.  Select the number of employees in each department (you only need to show the department code and the number of employees).
  22. 22.  Select the name and last name of employees working for departments with a budget greater than $60,000. Hint: Use ‘IN’ syntax to answer this query.  Select the departments with a budget larger than the average budget of all the departments.  Select the names of departments with more than two employees. Hint: Use ‘IN’ syntax to answer this query.  Add a new department called "Quality Assurance", with a budget of $40,000 and departmental code 11. Add an employee called "Mary Moore" in that department, with SSN 847-21-9811.  Reduce the budget of all departments by 10%.  Reassign all employees from the Research department (code 77) to the IT department (code 14).  Delete from the table all employees in the IT department (code 14).  Delete from the table all employees who work in departments with a budget greater than or equal to $60,000.
  23. 23. EXPERIMENT -4 REPORT of DATABASE MANAGEMENT SYSTEMS LAB. LAB GROUP 18 Written by AHMET ÖZDEMİR SOLUTIONS Bu haftaki laboratuvar föyünde bizlere IN &BETWEEN komutlarıyla ilgili bilgiler verildi. Yapılması istenen pre-lab ile önceki konuların tekrarını yapmakla birlikte daha önce işlemediğimiz bazı komutları da araştırmamız sağlandı. Select komutu ile birlikte kullanılan IN komutu istediğimiz değeri bulmamızda kolaylık sağlıyor. BETWEEN komutu ise istenen değerin hangi aralıklarda olması gerektiğine karar vermek için kullanılıyor. Bu komutlar dışında alıştırmaları yaparken UPDATE ve DELETE komutlarını ve nasıl kullanıldıklarını da öğrendik. UPDATE komutu ile istenen bir tablodan istediğimiz bir değeri değiştirmemize olanak tanır. DELETE komutu ise istenen bir tablodan istediğimiz bir satırı silmemizi sağlar. Bu komutların nasıl kullanıldığı yaptığımız pre-lab çözümünde belirtilmiştir. EXPERIMENT-4 1* -Aşağıdaki komut satırı ile lab_4 adında bir database oluşturduk: create database lab_4; -Daha sonra database’de aşağıdaki komutlar ile verilen bilgilere göre departments ve employees tablolarını oluşturduk: use lab_4; create table departments(Code int primary key,Name varchar(30),Budget money); create table employees (SSN int primary key,Name varchar(20),LastName varchar(20),Code int foreign key(Code) references Departments); 2* -Bu aşamada bize verilen değerler ile oluşturduğumuz tabloları doldurduk. use lab_4; insert into departments(Code,Name,Budget) values(14,'IT',65000) insert into departments(Code,Name,Budget) values(37,'Accounting',15000) insert into departments(Code,Name,Budget) values(59,'Human Resources',240000) insert into departments(Code,Name,Budget) values(77,'Research',55000); ****************************************************************************************** use lab_4; select * from departments;
  24. 24. ****************************************************************************************** use lab_4; insert into employees(SSN,Name,LastName,Code) values(123234877,'Michael','Rogers',14) insert into employees(SSN,Name,LastName,Code) values(152934485,'Anand', 'Manikutty', 14) insert into employees(SSN,Name,LastName,Code) values(222364883, 'Carol', 'Smith', 37) insert into employees(SSN,Name,LastName,Code) values(326587417, 'Joe', 'Stevens', 37) insert into employees(SSN,Name,LastName,Code) values(332154719, 'Mary-Anne', 'Foster', 14) insert into employees(SSN,Name,LastName,Code) values(332569843, 'George' , 'Odonnel' , 77) insert into employees(SSN,Name,LastName,Code) values(546523478, 'John' , 'Doe', 59) insert into employees(SSN,Name,LastName,Code) values(631231482,'David','Smith',77) insert into employees(SSN,Name,LastName,Code) values(654873219, 'Zacary', 'Efron', 59) insert into employees(SSN,Name,LastName,Code) values(745685214, 'Eric', 'Goldsmith', 59) insert into employees(SSN,Name,LastName,Code) values(845657245, 'Elizabeth', 'Doe' , 14) insert into employees(SSN,Name,LastName,Code) values(845657246, 'Kumar', 'Swamy', 14); ****************************************************************************************** use lab_4; select SSN,Name,LastName,Code as Department from employees; 3* -Tablolarımızı oluşturduktan sonra öğrendiğimiz yapıları kullanarak soruları yanıtladık: -Bütün çalışanların soyadlarını tekrarsız yazdırır: use lab_4; select LastName from employees group by LastName;
  25. 25. -Soyadı Smith ya da Doe olan çalışanların bilgilerini yazdırır: use lab_4; select SSN,Name,LastName,Code as Department from employees where LastName in ('Smith','Doe'); -37 ya da 77 nolu departmanda çalışanların bilgilerini yazdırır: use lab_4; select SSN,Name,LastName,Code as Department from employees where Code in (37,77); -Adı S ile başlayan çalışanların bilgilerini yazdırır: use lab_4; select SSN,Name,LastName,Code as Department from employees where LastName like 'S%'; -Departmanların toplam bütçesini yazdırır: use lab_4; select sum(Budget) from departments;
  26. 26. -Her bir departmanda kaç kişinin çalıştığını yazdırır: use lab_4; select Code as Department, count(SSN) as ÇalışanSayısı from employees group by Code; -Bütçesi 60000$ dan fazla olan departmanlarda çalışanların ad ve soyadlarını yazdırır: use lab_4; select Name,LastNamefrom employees where Code in (select Code from departments where Budget>60000); -Bütçesi ortalama bütçeden daha fazla olan departmanı ve bütçesini yazdırır: use lab_4; select Code, Budget from departments where Budget>(select avg(Budget) from departments); -İkiden fazla işçi çalıştıran departmanların adını yazdırır: use lab_4; select Name from departments where Code in (select Code from employees group by Code having count(Code)>2); -Yeni bir departman ve bu departmana yeni bir çalışan ekler: use lab_4; insert into departments(Code,Name,Budget) values(11,'Quality Assurance',40000) insert into employees(SSN,Name,LastName,Code) values(847219811,'Mary' ,'Moore',11); -Her bir departmanın bütçesini 10% oranında azaltır: use lab_4; update departments set Budget=Budget+Budget/10;
  27. 27. -77 kodlu departmanda çalışanları 14 kodlu departmana aktarır: use lab_4; update employees set Code=14 where Code=77; ****************************************************************************************** use lab_4; select SSN,Code as Department from employees; -14 kodlu departmanda çalışanları siler: use lab_4; delete from employees where Code=14; ****************************************************************************************** use lab_4; select SSN,Code as Department from employees; -Bütçesi 60000$ ya da daha büyük olan departmanlarda çalışanları siler: use lab_4; delete from employees where Code in (select Code from departments where Budget>=60000); use lab_4;select SSN,Code as Department from employees;
  28. 28. DATABASE MANAGEMENT SYSTEMS 2013-2014 FALL SEMESTER  Stored Procedure  A stored procedure is a collection of T-SQL statements that SQL Server compiles into a single execution plan.  Procedure is stored in cache area of memory when the stored procedure is first executed so that it can be used repeatedly. SQL Server does not have to recompile it every time the stored procedure is run.  It can accept input parameters, return output values as parameters, or return success or failure status messages. Syntax CREATE PROC[EDURE] procedure_name [ @parameter_name data_type] [= default] OUTPUT][,...,n] AS T-SQL_statement(s) Example 1 (Without parameters) CREATE PROC Departments_Members AS SELECT Dep_Name, COUNT(Emp_ID) NumberOfMember FROM Departments D, Employees E WHERE D.Dep_ID = E.Dep_ID GROUP BY Dep_Name Run Procedure Execute Departments_Members Example 2 (With parameters) CREATE PROC Department_Members @DeptName varchar(50) AS SELECT Dep_Name, COUNT(Emp_ID) NumberOfMember FROM Departments D, Employees E WHERE D.Dep_ID = E.Dep_ID and Dep_Name = @DeptName GROUP BY Dep_Name Run Procedure Execute Department_Members ‘Accounting’
  29. 29. Example 3 (Using RETURN ) CREATE PROC GROUPLEADER_MEMBERS @Emp_Code varchar(10) = null AS IF @Emp_Code is null BEGIN PRINT 'Please enter Employee Code!' RETURN END SELECT * FROM Employees WHERE EMP_EMP_ID = (SELECT EMP_ID FROM Employees WHERE Emp_Code = @Emp_Code) ORDER BY Emp_Name Update a Procedure ALTER PROC[EDURE] procedure_name [ @parameter_name data_type] [= default] [OUTPUT] [,...,n] AS t-sql_statement(s) Delete a Procedure DROP PROCEDURE procedure_name  Triggers A trigger is a special type of stored procedure that is executed automatically as part of a data modification. A trigger is created on a table and associated with one or more actions linked with a data modification (INSERT, UPDATE, or DELETE). When one of the actions for which the trigger is defined occurs, the trigger fires automatically. Following are some examples of trigger uses:  Maintenance of duplicate and derived data  Complex column constraints  Cascading referential integrity  Complex defaults  Inter-database referential integrity Syntax CREATE TRIGGER trigger_name ON <tablename> <{FOR | AFTER}> {[DELETE] [,] [INSERT] [,] [UPDATE]} AS SQL_Statement [...n]
  30. 30. Disable syntax Disable trigger <trigger_name> on <table_name> Enable syntax Enable trigger <trigger_name> on <table_name> There are two types of triggers  After triggers  Instead-of triggers After triggers: Fired when the SQL operation has completed and just before committing to the database.  Also known as "for-triggers" or just "triggers"  Defined by the keyword FOR CREATE TRIGGER tr_TownsUpdate ON Towns FOR UPDATE AS IF (EXISTS(SELECT * FROM inserted WHERE Name IS NULL) OR EXISTS(SELECT * FROM inserted WHERE LEN(Name) = 0)) BEGIN RAISERROR('Town name cannot be empty.', 16, 1) ROLLBACK TRAN RETURN END GO UPDATE Towns SET Name='' WHERE TownId=1 Instead-of triggers: Replace the actual database operations  Defined by using INSTEAD OF CREATE TABLE Accounts( Username varchar(10) NOT NULL PRIMARY KEY, [Password] varchar(20) NOT NULL, Active CHAR NOT NULL DEFAULT 'Y') GO CREATE TRIGGER tr_AccountsDelete ON Accounts INSTEAD OF DELETE AS UPDATE a SET Active = 'N' FROM Accounts a JOIN DELETED d ON d.Username = a.Username WHERE a.Active = 'Y' GO
  31. 31. User-Defined Functions  Scalar functions (like SQRT(…)) Similar to the built-in functions  Table-valued functions Similar to a view with parameters Return a table as a result of single SELECT statement  Aggregate functions (like SUM(…)) Perform calculation over set of inputs values Defined through external .NET functions  To create / modify / delete function use: CREATE FUNCTION <function_name> RETURNS <datatype> AS … ALTER FUNCTION / DROP FUNCTION Example CREATE FUNCTION ufn_CalcBonus(@salary money) RETURNS money AS BEGIN IF (@salary < 10000) RETURN 1000 ELSE IF (@salary BETWEEN 10000 and 30000) RETURN @salary / 20 RETURN 3500 END Inline Table-Valued Functions Example Defining the function USE Northwind GO CREATE FUNCTION fn_CustomerNamesInRegion ( @regionParameter nvarchar(30) ) RETURNS TABLE AS RETURN ( SELECT CustomerID, CompanyName FROM Northwind.dbo.Customers WHERE Region = @regionParameter ) Calling the function with a parameter SELECT * FROM fn_CustomerNamesInRegion(N'WA')
  32. 32. Multi-Statement Table-Valued Function – Example CREATE FUNCTION fn_ListEmployees(@format nvarchar(5)) RETURNS @tbl_Employees TABLE (EmployeeID int PRIMARY KEY NOT NULL, [Employee Name] Nvarchar(61) NOT NULL) AS BEGIN IF @format = 'short' INSERT @tbl_Employees SELECT EmployeeID, LastName FROM Employees ELSE IF @format = 'long' INSERT @tbl_Employees SELECT EmployeeID, (FirstName + ' ' + LastName) FROM Employees RETURN END Experiment 5 These questions refer to several tables in the AdventureWorks sample database. Download the AdventureWorks sample database and then create the following queries: 1) Write a function that retrieves the average commission percent for the SalesPerson table. 2) Write a function that retrieves the count of all Male Employees that excepts Male as a parameter. 3) Write a function that retrieves the highest List Price of any Product. 4) Write a function that retrieves the length of all Descriptions in the ProductDescription table. Hint: Use LEN syntax for this query. 5) Write a stored procedure that retrieves the Currency Code and the first 3 letters of the Currency Name as 'AB'. Hint: Use LEFT syntax for this query. 6) Write a stored procedure that list the JobTitle, Gender, and Lowest Login Id for each group of Employees grouped by the following titles: ‘Buyer', 'Recruiter' or 'Stocker'. Define the titles as parameters for this stored procedure. 7) Write a stored procedure that list the Product Sub Category IDs from the Product table; include only those subcategories that occur more than 20 times. In addition to the ID also return the first product name in alphabetical order and the highest price for products in this subcategory. Send 20 as a parameter for this stored procedure. 8) Write a trigger that writes a message after insert a record into the Product table. 9) Write a trigger that inserts a record into a table named deleted after deleting a record from the Product table.
  33. 33. EXPERIMENT -5 REPORT of DATABASE MANAGEMENT SYSTEMS LAB. LAB GROUP 18 Written by AHMET ÖZDEMİR SOLUTIONS Bu haftaki laboratuvar föyünde bizlere stored procedure, function ve trigger’lar hakkında bilgiler verildi. Yapılması istenen pre-lab ile önceki konuların tekrarını yapmakla birlikte yeni öğrendiğimiz bazı komutları da araştırmamız sağlandı. Her defasında yeni bir komut girmektense, ekrana getirmek istediğimiz bilgiyi stored proceure olarak kaydedersek hem sonuca daha hızlı ulaşırız hemde aynı komut defalarca çalıştırılmamış olur. Aynı mantığı function için de söylemek mümkün. İşleyiş mekanizmaları da oldukça benzemektedir. Triggerlar ise veri değisiminin hemen ardından devreye giren özel bir stored procedure gibi yapılardır . Insert , update, delete işlemlerinden sonra devreye girerler. Ayrıca after triggers ve instead-of triggers olmak üzere iki tür trigger olduğunu öğrendik. After triggerlar sadece tablolar üzerinde tanımlanabilirler. Instead of triggerlar ise hem tablolar hem viewlar üzerinde tanımlanabilirler. Bu komutların nasıl kullanıldığı yaptığımız pre-lab çözümünde belirtilmiştir. EXPERIMENT-5 1* - Oluşturduğumuz exp1 adındaki fonksiyon Sales.SalesPerson tablosundaki ortalama komisyon tutarını verir: go create function exp1() returns table as return(SELECT AVG(CommissionPct) as AverageCommission from Sales.SalesPerson) select * from exp1();
  34. 34. 2* - Oluşturduğumuz exp1(@gender) adındaki fonksiyon HumanResources.Employee tablosundan, girdiğimiz cinsiyete mensup kişileri sayar ve ekrana bastırır: go create function exp2(@gender varchar(1)) returns table as return( SELECT count(*) as Number FROM HumanResources.Employee where Gender=@gender ) select * from exp2('M'); 3* - Oluşturduğumuz exp3 fonksiyonu Production.Product tablosundaki maksimum tutarı verir: go create function exp3() returns table as return( SELECT Max(ListPrice) as MaximumPrice FROM Production.Product) select * from exp3(); 4* - Oluşturduğumuz exp4 fonksiyonu Production.ProductDescription tablosundaki tüm description boyutlarını verir: go create function exp4() returns table as return (SELECT LEN(Description) as Description FROM Production.ProductDescription) - Çıktısında 762 satırlık bir tablo aldım. Bir kısmı:
  35. 35. select * from exp4(); 5* - Oluşturduğumuz CurrencyCode store procedure, Sales.Currency tablosundaki her bir currency code sahibinin isimlerinin ilk üç harfini ekrana verir: CREATE PROCEDURE CurrencyCode AS SELECT CurrencyCode,LEFT(Name,3) as AB FROM Sales.Currency GO execute CurrencyCode; - Çıktısında 105 satırkık bir tablo aldım. Bir kısmı: 6* - Oluşturduğumuz Exp6 store procedure, HumanResources.Employee tablosundaki Buyer, Recruier ya da Stocker JobTitle’ye sahip kişilerin en kısa ID’ye sahip olanlarını verir: CREATE PROCEDURE Exp6 AS SELECT JobTitle,MIN(LoginID) as Login from HumanResources.Employee where JobTitle IN('Buyer','Recruiter','Stocker') group by JobTitle GO execute Exp6;
  36. 36. 7* - Oluşturduğumuz Exp_7_2 @number store procedure, ProductSubcategoryID tablosundan id’leri girdiğimiz sayıdan daha çok tekrar eden kategorileri verir: CREATE PROCEDURE Exp7_2 @number int AS SELECT ProductSubCategoryID,MIN(Name) as Name,Max(ListPrice) From Production.Product group by ProductSubcategoryID having count(ProductSubcategoryID)>@number order by Name GO execute Exp7_2 20; 8* - Production.Product tablosuna yeni bir ürün kaydı gerçekleştiğinde 'New product enrolled’ mesajını verir. create trigger exp8_1 on Production.Product after insert as begin print 'New product enrolled' end

×