Create Store procedures

Store procedure has some similarities with views in the sense that it allows encapsulation. i.e. to retrieve for further, later use a series of commands, like the select command.
With store procedure, it is possible to branch. It means you can get different statements to run based on specific requirements.
The begin and the end is compulsory in store procedure as it shows where the query starts and where it ends.
Note, you can use a select statement and create a procedure out of it.  Likewise, you can do with views.
The Store procedure is used as data access layer, which means that it could access the data without going to the table directly.

Let use the table schema below, to learn more about store procedure.


The TABLE_NAME is tblEmployee and has 7 columns under the COLUMN_NAME, each column will have data.

Step 1. 

Create Procedure and Execute

We will be using the table tblEmployee to create a procedure out of it.
In order to create and execute procedure, the following commands are used.


The create procedure command, created a procedure with three columns, EmployeeNumber, EmployeeFirstName and EmployeeLastName out of the seven columns in the table tblEmployee.
And the execute or exec commands execute the created procedure  and return the data as we can see below.


Note aside from the two execute command shown before, it is possible to return data from store procedure also by just using the name of the store procedure simply like:

EmployeesName 

without the execute or exec preceding it. But this can only be done after the end of a batch and go ends a batch, so it has to be after the go statement.

Step 2.

Create Procedure and Return data based on Input

The procedure we created at step 1 returns all the data for the employee three columns that we specified. Supposed we don't want this to happen, and we only want the return data based on a given input then how can this be achieved?

Let see that in action.
first I will drop the procedure that I have created earlier
There are things to put into consideration while dropping the procedure, 
  1.  You can't drop procedure and drop it again - (with same name)
  2. You can't create procedure and create it again - (with same name)
So we need to test it to make sure if exist or not and based on that we can perform the necessary actions.

Check if procedure exists before dropping the procedure.




The code above will return employee based on the given EmployeeNumber, that was passed in as an augment of integer type.
















How to use IsNull in T-SQL

The IsNull method is a built-in function that takes two parameters. The first parameter is the expression or variable that the IsNull method checks and return true if the variable contains Null. The second parameter is the replacement value that the IsNull method returns if the expression is Null.

Below is an instance of a table with Null 
 

















The student table contains student numbers and student names, and there are NULL in rows 3, 8 and 10.
Those three rows represent the case where there could be NULL in the database table.

Step 1.


To use the Isnull method, let us declare a variable StudentName and set it to Null.

Like this:  declare @StudentName as nvarchar(10) = Null

Then let use the Isnull method to check for the variable value, like this:
 
select Isnull(@StudentName, 'No name') as StudentName

By now you should know the result we are expecting right?

When we run the two lines of code together 


what happened is this:

If the StudentName is not equal to Null it returns the student name otherwise it returns No Name.

Step 2. 


The Isnull method can select all the Nulls in tblStudent1 and replace it with 'No Name'.





The code above replaces three rows 3, 8 and 10 in the student table with No Name instead of Null.

















This shows that you can also use the Isnull method to create table.
Note that Isnull is faster than coalesce and it is also better than coalesce where you've got two different types of  data type.

Creating an AFTER trigger

To understand what the trigger is, see it as automation. It fires whenever an event occurs.
A good example is an automated email that is sent out whenever someone submitted a form or registered to a website.

Trigger in SQL server act the same way. It is activated based on certain conditions.

We will use the table tblStudent below to explain the trigger.


You can read how to create this table here.

Step 1.

Create a Trigger for tblStudent table


To create a trigger for a table or view the following SQL syntax are used.

-- SQL Server Syntax  
-- Trigger on an INSERT, UPDATE, or DELETE statement to a table or view (DML Trigger)  
  
CREATE TRIGGER trigger_name   
ON { table | view }   
{ FOR | AFTER | INSTEAD OF }   
{ [ INSERT ] [ , ] [ UPDATE ] [ , ] [ DELETE ] }     
AS { sql_statement  [ ; ] [ ,...n ] | EXTERNAL NAME <method specifier [ ; ] > }  

Now let use the above syntax to create a trigger for the student table.

If the above step is executed correctly then it created a trigger inside the Triggers folder on the dbo.tblStudent.



Step 2.

Delete Data and Roll it Back


Now let us write an SQL delete statement to delete from the tblStudent where StudentNumber equals 1.


Execute the code and you will see two results. 
The first one is empty and the second is with the data that we tried to delete.
Trigger prints the two results based on the two select statements in the trigger named tr_tblStudent that we have created in step 1. The first select returns table with empty data because we haven't inserted any data.
The second select returns the data we tried to delete which did not delete anyways because of the rollback tran.



So note, we executed the delete statements then trigger fires up and prints the results.







Difference between Delete and Truncate

Delete

Removes the records and remember the last primary key of the removed records.
This will allow the next records that will be inserted to start from the next number of the last deleted record.

For instance, if you create a table tblStudent with two columns:

Step 1

Create table tblStudent
(StudentNumber int Constraint PK_tblStudent PRIMARY KEY IDENTITY(1,1),
StudentName nvarchar(20))

StudentNumber - that has an int type, a constraint PK_tblStudent  and serves as the Primary Key with identity(1,1). The identity(1, 1) helps you to incrementally assign primary key starting from 1 without manually inserting those.

StudentName - that has just an nvarchar(20)

Step 2

Then use the insert  to insert into tblStudent values ('Maxy'), ('Byte')
once inserted it shows a table like this:

Step 3

Then use the delete to delete from tblStudent, then the two records will be deleted
as you can see below:



Because you have deleted the record using delete, now when inserting new records the last primary key number deleted was taken into remembrance and new records studentNumber start from the next number of the previously deleted number. To see that proceed to step 4. Note, this isn't the same when the records are truncated.

Step 4

Insert again using the insert into tblStudent values ('Maxy'), ('Byte').

This time what do you expect to see at StudentNumber column, 1 and 2 ? no that is wrong, it will come as 3 and 4.

                                           

If  I had used truncate to remove the records intially before inserting a new one then what would have happened? will it still come as 3 and 4 or 1 and 2 next time? 

Yes it will come 1 and 2. 

What is Truncate then?

TRUNCATE

Removes the records but never remember the last primary key of the removed records. This will allow the next records that will be inserted to start from the beginning again.
 
To verify this, instead of using delete at Step 3, do the same for truncate , with command 

truncate table tblStudent

Then repeat Step 4 to insert a new record, once inserted,  It shows a table where the StudentNumber start from the beginning and not from 3 down to 4 but from 1 down to 2:













TSQL-Working With Date And Time

Here you will learn how to work with the date and time in SQL Server.

select  GETDATE() as dateNow
This returns the current date and time.

select CURRENT_TIMESTAMP as dateNow
This also return the current date and time.

select SYSDATETIME() as dateNow
This return the current date and its more accurate. 

select datename(WEEKDAY, GETDATE()) as weekDay
This return the current weekday from the current date and time

select DATEADD(YEAR, 1, GETDATE()) as nextYear
This allow adding extra year to the current year.

select DATEDIFF(SECOND, '1984-09-07 12:24:08', GETDATE()) as monthsElapsed
The DateDiff  takes the time unit, the early date , the later date and return the months elapsed. 
The DateDiff shows the difference between two dates.

select DATEPART(hour, '2020-01-02 12:20:05') as theHour
This select the hour of the current date and time


Converting from dates to strings

declare @mydate as datetime = '2021-07-27 03:15:04.453'

select 'The date and time is: ' + @mydate

go

declare @mydate as datetime = '2021-07-27 03:15:04.453'

select 'The date and time is: ' + convert(nvarchar(20),@mydate,104) as convertedDate

go

declare @mydate as datetime = '2021-07-27 03:15:04.453'

select cast(@mydate as nvarchar(20)) as castDate

select try_convert(date,'Tuesday, 27 July 2021') as convertedDate

select parse('Tuesday, 27 July 2021' as date) as parsedDate

select format(cast('2021-07-27 03:15:04.453' as datetime),'D') as formattedLongDate

select format(cast('2021-07-27 03:15:04.453' as datetime),'d') as formattedShortDate

select format(cast('2021-07-27 03:15:04.453' as datetime),'dd-MM-yyyy') as formattedBritishDate

select format(cast('2021-07-27 03:15:04.453' as datetime),'D','zh-CN') as formattedInternationalLongDate


Date offsets

declare @myDateOffset as datetimeoffset(2) = '2021-07-27 03:15:04.453 +03:00' 

select @myDateOffset as dateOffset

go

declare @myDate as datetime2 = '2021-07-27 03:15:04.453'

select TODATETIMEOFFSET(@myDate,'+03:00') as dateOffset

select DATETIME2FROMPARTS(2015,06,25,1,2,3,456,3)

select DATETIMEOFFSETFROMPARTS(2015,06,25,1,2,3,456,5,30,3) as dateOffset

select SYSDATETIMEOFFSET() as timeNowWithOffset;

select SYSUTCDATETIME() as timeNowUTC;

declare @myDateOffset as datetimeoffset = '2021-07-27 03:15:04.453 +03:00'

select SWITCHOFFSET(@myDateOffset,'-03:00') as dateOffsetTallinn

 



TSQL- How to remove a character from a string


A string is a group of characters in a specified order, called sequence of characters.
This sequences are zero-indexed.

To remove a character from a string in TSQL use SUBSTRING.
The substring is a built-in function that takes, expression, starting point and length of the expression.
Based on those three parameters, it decides on what string to return



To remove the last character, what do you have to do?

Think about it, all you need to do is change the starting point value from 2 to 1.

CONCAT String With TSQL


Joining strings together

We will declare three variables and set their values, then the various select statement will be use for joining the string and print the outcome.

declare @firstname as nvarchar(20)
declare @middlename as nvarchar(20)
declare @lastname as nvarchar(20)

set @firstname = 'Maxybyte'
set @middlename ='Technologies'
set @lastname = 'Program'

select @firstname + ' ' @middlename +  ' '  + @lastname as FullName

FullName 
Maxybyte Technologies Program

What happens when you are adding three string while just two strings are set? then you get a Null as answer.

declare @firstname as nvarchar(20)
declare @middlename as nvarchar(20)
declare @lastname as nvarchar(20)

set @firstname = 'Maxybyte'
set @lastname = 'Program'

select @firstname + '  ' iif(@middlename is null, '', '  '  + @middlename+  '  '  + @lastname as FullName

FullName
Maxybyte Program

The following select statement can also be used.
select @firstname + CASE WHEN @middlename IS  NULL THEN ''  ELSE '  '  + @middlename END +  '  '  + @lastname as FullName

FullName
Maxybyte Program

The following select statement can also be used.
select @firstname + coalesce('  '  + @middlename, ") +  '  ' + @lastname as FullName

FullName
Maxybyte Program

The best use case for the select statement to join two string together is the CONCAT method
select CONCAT(@firstname, '  '  +  @middlename,  '  ', @lastname as FullName
 


 

Python Testcases and Testsuite in 38 minutes

In this video we are going to dive in quickly into something that mostly confuse some people that are just learning software testing. What are testcases and what are the purpose of testsuites? How are they use together? e.t.c. Find out in this video by watching it. Enjoy learning!

How to use Interactive Console to store data into database

In this tutorial, I will briefly write on how to use the Interactive Console in PyCharm to add data into a database.

Let us use the models below and populate data into the language field using the interactive console in PyCharm :

from django.db import models

# Create your models here.
class Language(models.Model): language_name = models.CharField(max_length=264, unique=True) def __str__(self): return self.top_name class Webpage(models.Model): language = models.ForeignKey(Language, on_delete= models.CASCADE) name = models.CharField(max_length=264, unique=True) url = models.URLField(unique=True) def __str__(self): return self.name class Record(models.Model): name = models.ForeignKey(Webpage,on_delete=models.CASCADE) date = models.DateField() def __str__(self): return str(self.date)

Now let us Add data to Language field

Step 1. use command python manage.py shell
Step 2. Import the class or field to add data into, e.g, from  app_name.models import class_name
Step 3. Create an instance of the class_name, e.g  L = Language(lan_name = "Python")
Step 4. L.save()
Step 5 print(Language.objects.all())

The last step prints what has been saved in the database.

Then type python manage.py runserver, if everything is working fine then you should see the following:

System check identified no issues (0 silenced).
June 11, 20-- - 16:28:01
Django version 3.0.7, using settings 'first_project.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.

However, In order to fully use the database and the Admin, we will need to create a “superuser”

We can do this with the following:
        python manage.py createsuperuser

Then go to the following link, http://127.0.0.1:8000/admin and log in with your superuser details and you should see your data inside the field you have added it to. In our case the Language field.


Watch this.




Create table in MS Access

HOW TO CREATE TABLE IN MS ACCESS

I will show how to create tables base on the following diagram and it's textual specification.
You can do this same process by using MS Access.
In order to create a database that contains these two tables, let's use the following code after this diagram.

Description of database tables created by using Enterprise Architect CASE tool

Solution:

CREATE TABLE Occupation(
occupation_code SMALLINT NOT NULL,
name VARCHAR(50) NOT NULL,
max_working_hours_in_week SMALLINT=40 NOT NULL,
min_sal CURRENCY NOT NULL,
CONSTRAINT pk_occupation PRIMARY KEY(occupation_code),
CONSTRAINT ak_occupation_name UNIQUE (name));

CREATE TABLE Worker(
occupation_code SMALLINT NOT NULL,
worker_id AUTOINCREMENT,
birth_date DATETIME NOT NULL,
address VARCHAR(255) NOT NULL,
registr_time DATETIME DEFAULT Now NOT NULL,
is_active YESNO DEFAULT TRUE NOT NULL,
given_name VARCHAR(255) NOT NULL,
surname VARCHAR(255) NOT NULL,
CONSTRAINT pk_worker PRIMARY KEY(worker_id)
);

The tables help to implement a system that can be analyzed with the following statements.
  •   Each worker has exactly one occupation. 
  •   Each occupation is carried by zero or more workers.
Note that the SQL standard does not describe the type CURRENCY. Instead, one can use the type Decimal.

Column is_active of the table worker must contain the truth values TRUE or FALSE  and in MS access YESNO  is the name of the type that contains these values.

If one changes the occupation code in a row of the table Occupation, then the system should extend this change to the table Worker (ON UPDATE CASCADE compensating action in the specification of the foreign key constraint.

Note that Table Occupation contains reference data. which is the data that defines the set of permissible values that other data fields can use. Meanwhile, Table Worker contains master data. Master data its self represents the business objects that are agreed on and shared across the enterprise. 

SQL Question:

  1. Find the average price of flats, the minimal price of flats, maximal price of flats, the number of flats, the sum of flat prices,  the price of which is registered, and the difference between the maximal and the minimal price. In the resulting table the corresponding columns must have names avg_price, minimal_price, maximal_price, sum_of_prices, number_of_flats_with_price, range_of_prices.
Solution:

SELECT Format(Avg(price),'\€#,##0.00') AS avg_price, 
Format(Min(price),'\€#,##0.00') AS minimal_price, 
Format(Max(price),'\€#,##0.00') AS maximal_price, 
Format(Sum(price),'\€#,##0.00') AS sum_of_prices, Count(price) AS number_of_flats_with_price, 
Format(Max(price)-Min(price),'\€#,##0.00') AS range_of_prices
FROM Flat;

Query Result:
Query Result
2. Find the number of hotels in Lagos. The resulting table must contain exactly one column with the name cnt
Solution:
SELECT Count(*) AS cnt

FROM Hotel WHERE city = 'Lagos';

3. Find the numbers of hotels where it is at least one reservation.Duplicate lines must be removed from the result.
Solution:
SELECT hotel_nr
FROM Reservation
GROUP BY hotel_nr;

OR

SELECT DISTINCT hotel_nr
FROM Reservation;

4. Find rooms that cost more than 400 naira for a night. Find data from all the columns of the table Room. In case of each found room, present also the name of the hotel where the room is situated
Solution:
SELECT Room.*, Hotel.hotel_name AS hotel
FROM Hotel, Room
WHERE Hotel.hotel_nr=Room.hotel_nr And Room.price>400;


5Find the number of courses and their average number of credit points, in case of courses that comments are missing, the name ends with y, and the number of credit points is not 1. The result must be a table with one row and two columns. The names of the columns must be cnt and average, respectively.

Solution:
SELECT Count(*) AS cnt, Avg(credit_points) AS average
FROM Course
WHERE Course.comments IS NULL
AND Course.course_name Like '%y'
AND credit_points <> 1;

6. Calculate the value of the following expressions:  331+ 5587  879/54  (879/54) – round the result so that there are only two numbers after comma  (233-24)*565  2^3
Solution:
SELECT 331+5587 AS expr1,
879/54 AS expr2,
Round((879/54),2) AS expr3,
(233-24)*565 AS expr4, 2^3 AS expr5;

7. Find all the data about reservations. For each reservation, find also the concatenated given name and surname of the associated guest (in the column guest_name) as well as the name of the hotel where the reservation is made. Sort the results based on the hotel name in descending alphabetical order. If there are more than one reservation in the same hotel, then sort these rows based on the guest number in the ascending order. Use in the query correlation names (aliases) G, R, and H to reffer to the tables Guest,
Reservation, and Hotel, respectively.
Solution:
SELECT R.*,
trim(G.given_name&' '& G.surname) AS guest_name,
H.hotel_name FROM Reservation AS R ,
Guest AS G,
Hotel AS H
WHERE ((R.guest_nr = G.guest_nr) And (R.hotel_nr = H.hotel_nr))
ORDER BY hotel_name DESC, G.guest_nr;

8.Find the number of reservations in case of each hotel. For each hotel, present the hotel number, hotel name, and the number of reservations. If there are no reservations in a hotel, then the number of reservations must be 0. The column containing data values that represent the number of reservations must have the name cnt. Sort the results based on the number of reservations in the descending order.

Solution:

SELECT Count(Reservation.hotel_nr) AS cnt, 
Hotel.hotel_nr, Hotel.hotel_name
FROM Hotel LEFT JOIN Reservation
ON Hotel.hotel_nr = Reservation.hotel_nr
GROUP BY Hotel.hotel_nr, Hotel.hotel_name
ORDER BY Count(Reservation.hotel_nr) DESC;

9. Find all the data of hotels (from all the columns of the table Hotel) that have no associated reservations.

Solution:

SELECT *
FROM Hotel
WHERE hotel_nr <>ALL (SELECT hotel_nr FROM Reservation WHERE hotel_nr IS NOT NULL);

10. Insert to the table Guest_backup all the data about the guests (from the table Guest) whose address contains the word "Lagos" or whose address is not registered. Please note that table Guest_backup must contain concatenated given name and surname of guests. In case of concatenating string remove from the result leading and trailing spaces by using Trim function.

Solution:

INSERT INTO Guest_backup(guest_nr, guest_name,address) SELECT guest_nr, trim(given_name &' '& surname) AS guest_name, address FROM Guest WHERE address LIKE '%Lagos%' OR address IS NULL;

11. Create a copy of the table Reservation by using a SELECT … INTO statement. The name of the copy table must be Reservation_backup

Solution:

SELECT * INTO Reservation_backup FROM Reservation;

12. Define the primary key constraint in the table Reservation_backup that involves columns hotel_nr, room_nr, guest_nr, and beginning_date (in the specified order). The name of the primary key constraint must be pk_reservation_backup.

Solution:

ALTER TABLE Reservation_backup ADD CONSTRAINT pk_reservation_backup PRIMARY KEY(hotel_nr, room_nr, guest_nr, beginning_date);

13. Delete from the table Reservation_backup data about all the reservations that have started more than 1500 days ago in the hotel "Sheraton".

 Solution:

DELETE *
FROM Reservation_backup
WHERE beginning_date >Date() - 1500 AND
hotel_nr IN (SELECT hotel_nr
FROM Hotel
WHERE hotel_name='Sheraton');

14. Delete from the table Reservation_backup data about all the end dates of reservations where such dates are registered. In case of all the modified rows register also a comment: "End date is removed at X", where X is the current timestamp. The comment must be appended to the existing comment. The current timestamp must be found by using a function.

Solution:

UPDATE Reservation_backup 
SET 
end_date = NULL, 
comment = trim(comment & ' End date is removed at ' & Now())
WHERE 
end_date IS NOT NULL;

15. Modify the data of a guest with number 6 so that new address is "Lagos, Ikeja 13-05". Do it only if the guest has no reservations that have started during the last 300 days.

Solution:

UPDATE Guest SET address = 'Lagos, Ikeja 13-05' 
WHERE guest_nr=6 AND NOT EXISTS
(SELECT * FROM Reservation 
WHERE Reservation.guest_nr = Guest.guest_nr AND Reservation.beginning_date>Date()-300);

16. Find the numbers of guests who have made more than two reservations:

Solution:

SELECT guest_nr
FROM Reservation
GROUP BY guest_nr
HAVING Count(*)>2;

17. Find all the data of all the guests who have made the biggest number of reservations. In addition to the data of guests, present also the number of their reservations. 

Solution:

SELECT Guest.guest_nr, Guest.given_name, Guest.surname, Guest.address, Count(Reservation.guest_nr) AS cnt
FROM Guest INNER JOIN Reservation ON Guest.guest_nr=Reservation.guest_nr
GROUP BY Guest.guest_nr, Guest.given_name, Guest.surname, Guest.address
HAVING Count(Reservation.guest_nr)>=ALL(SELECT Count(*) AS cnt FROM Reservation GROUP BY guest_nr);

18. Find all the learnings that started in 1999 and finally completed with a successful exam (the result is 4 or 5). It is possible that a successful exam was done only after more than one attempt. Present data from all the columns of the table "Learning". The result must contain exactly one row for each learning that satisfies the criteria. In addition, the result must contain the given name and the surname of the student, presented as one string and a space between the names. The result must also contain the surname of the lecturer and the name of the course. Order the result based on the surnames of students in alphabetical order. If there are more than one row with the same surname, then order these rows based on the names of courses in alphabetical order.

Solution:

SELECT Learning.learning, Learning.student, Student.given_name & ' ' & Student.surname AS student_name, Learning.course, Course.course_name, Learning.lecturer, Lecturer.surname AS lecturer_name, Learning.start_date, Learning.end_date
FROM Course INNER JOIN ( Lecturer INNER JOIN (Student INNER JOIN Learning ON Student.student_code=Learning.student) ON Lecturer.lecturer_code = Learning.lecturer) ON Course.course_code = Learning.course WHERE Year(start_date)=1999 AND EXISTS (SELECT * FROM Exam WHERE Exam.learning= Learning.learning AND result IN (4,5))
ORDER BY Student.surname, Course.course_name;

19. Register comment "Has to finish soon!" in case of students whose curricula code starts with the letters "MP" and who were admitted before the beginning of 1996. If there is already a comment in case of a student,  then the new comment should not replace it. Instead, the new comment must be placed in front of the existing comment.

Solution:

UPDATE Student SET comment = Trim( 'Has to finish soon! ' &  comment)
WHERE Year(admission_time)<1996 AND curricula LIKE 'MP%';












New Post

Create Store procedures

Store procedure has some similarities with views in the sense that it allows encapsulation. i.e. to retrieve for further, later use a series...