This returns the current date and time.
Converting from dates to
declare @mydate as datetime = '2021-07-27 03:15:04.453'
select 'The date and time is: ' + @mydate
declare @mydate as datetime = '2021-07-27 03:15:04.453'
select 'The date and time is: ' + convert(nvarchar(20),@mydate,104) as convertedDate
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
declare @myDateOffset as datetimeoffset(2) = '2021-07-27 03:15:04.453 +03:00'
select @myDateOffset as dateOffset
declare @myDate as datetime2 = '2021-07-27 03:15:04.453'
select TODATETIMEOFFSET(@myDate,'+03:00') as dateOffset
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
Joining strings together
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 fieldStep 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
|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,
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.
- 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.
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
3. Find the numbers of hotels where it is at least one reservation.Duplicate lines must be removed from the result.
GROUP BY hotel_nr;
SELECT DISTINCT hotel_nr
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
SELECT Room.*, Hotel.hotel_name AS hotel
FROM Hotel, Room
WHERE Hotel.hotel_nr=Room.hotel_nr And Room.price>400;
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
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.
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.
SELECT Count(Reservation.hotel_nr) AS cnt,
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.
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.
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
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.
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".
WHERE beginning_date >Date() - 1500 AND
hotel_nr IN (SELECT hotel_nr
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.
end_date = NULL,
comment = trim(comment & ' End date is removed at ' & Now())
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.
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:
GROUP BY guest_nr
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.
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.
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.
UPDATE Student SET comment = Trim( 'Has to finish soon! ' & comment)
WHERE Year(admission_time)<1996 AND curricula LIKE 'MP%';
Recursion is one of the most useful aspects of subroutines; that is the ability of the procedure or subroutine to call itself.
Download: Application to calculate your days on Earth
This article will use a rather ancient puzzle known as the Tower of Hanoi originated from Hindu.
|Diagram Tower of Hanoi|
- We are interested in moving the rings from A to B, perhaps using C in the process.
- Also by the rules of the game, rings are to be moved one at a time
- At no point may the larger ring be placed on top a smaller one.
- move A to B;
- move A to C;
- move B to C;
- move A to B;
- move C to A;
- move C to B;
- move A to B;
- if N is 1 then print "move A to B";
- else( If N is greater than 1) do the following:
2.2 call move 1 from A to B using C;
2.3 call move N - 1 from C to B using A;
After the function; below are the 3 Steps our code follows:
Below also are the meaning of the variables selected:P = denotes procedure/subroutine
If N is greater than 1:
Step1 says: move top (N -1) rings from Beg to Aux peg.
Step2 says: move 1 ring from Beg to End peg.
Step3 says: move top (N-1) rings from Aux to End peg.
static void Main(string args)
char beg_fromPeg = 'A'; // Begining of the tower in output where we move from
char dest_Peg = 'B'; // end tower in output where we move to
char via_PegtoDest = 'C'; // auxilliary tower in output through which we move
int disks = 3; // number of disks to move around
solverHanoiTowers(disks, beg_fromPeg, via_PegtoDest, dest_toPeg);
private static void solverHanoiTowers(int n, char beg_fromPeg, char via_PegtoDest, char dest_toPeg)
if ( n == 1)
Console.WriteLine("move" + beg_fromPeg + "to" + dest_Peg);
solverHanoiTowers(n - 1, beg_fromPeg, dest_Peg, via_PegtoDest);
solverHanoiTowers(1, beg_fromPeg, via_PegtoDest, dest_Peg);
solverHanoiTowers(n - 1, via_PegtoDest, beg_fromPeg, dest_Peg);
move A to C;
move B to C;
move A to B;
move C to A;
move C to B;
move A to B;
These processes below is the sequential flow that moves all the rings in peg A to B recursively.
P( 3 , A, B, C)
/ 1st Chain 2nd Chain 3rd Chain
P(2, A, C, B) - Step 1,2,3. P(2 , A, C, B) P(1,A, B, C)= A to C P(2, B, A, C)
/ / /
P(1, A, B, C) - Step 2. P(1, A, B, C) = A to C P(1,B,C,A)= B to A
/ / /
P(2, B, A, C) - Step 1,2,3. P(1, A, C, B)= A to B P(1,B,A,C)= B to C
P(1, C, A, B)= C to B P(1, A, B, C) = A to C
Here what happened is that we applied those 3 steps on P(3, A, B, C) and those are the chain we got out of it that gave us the accurate result in code.
Follow maxybyte on social media.
Read: Class and Object -Object-Oriented Programming
A maintenance-driven approach is better than tools-driven approach; although with the tools-driven approach, it's easy to get the work done once you know how to make use of the tools also tools-driven approach is good for departmental application development.
In a nutshell, many applications are more scope beyond that of a departmental level where you will anticipate changes often-Enterprise level. Here you will learn how to use a maintenance driven approach to creating a database that could anticipate changes. Using this approach involves the logical separation of concerns, where the presentation, domain, and the persistence layers need to work together to get the work done.
Then rename this project to LocalDbMDA.Presentation, This layer present the end result of the application to the end user.
Then named the new file LocalDbMDA.Persistence. Repeat this step to create LocalDBMDA.Domain, right after this press Cltr+Shift+B which is the shortcut key to build a solution.
layer, which will keep the dependency chain central to the Domain layer, like this:
In order to facilitate the development of a system in a piecemeal fashion and simplify making changes in the system, its decomposition into subsystems must follow the advice of patterns of assigning responsibilities (General Responsibility Assignment Software Patterns, GRASP) like Low Coupling and High Cohesion.
Low Coupling means in this context that a subsystem should not depend too much on other subsystems. It helps us to achieve low dependency of subsystems, low change impact of subsystems, and increased reuse of the artifacts that are created during the development of subsystems.
High Cohesion means in this context that the responsibilities of a subsystem must be strongly related in order to reduce the complexity of subsystems.
These rules are applicable to creating of a database.
Database is a set of true propositions (facts) about the real world.
Propositions contain representation of values (data) and their interpretation.
Examples of propositions.
A car manufacturer has a numeric identifier 1 and a textual name "Toyota".
A car manufacturer has a textual name "Mitsubishi", numeric id = 2 and its description is "Rarity".
Of course, it is very easy to build applications ruining on local computers and accessing stored database directly also on the local database should be very easy. One out of the reasons we build an application is to make it accessible worldwide, and we could get this possibility through the help of the internet.
- Schema migration from the on-premises database to SQL Azure
- Table data migration from the on-premises database to SQL Azure
|Database LocalDB Diagram|
We need to create a new SQL Azure database that we can use for the migration. We can create a new SQL Azure database via the window Azure platform management in Azure portal but we are already in Management studio, let's do it there.
In that case, we just need to open a new connection to our exciting Azure database server, If you haven't signed up you can do that in Azure portal.
|SQL Server Diagram|
Copy and paste this code to create the database named MYCloudOki:
CREATE DATABASE MyCloudOki
To migrate our schema from on-premises to Azure database destination, we will right_click on the
database we want to move the schema , => Tasks => Generate Scripts..
Then follow the instructions.
When you get to the Advance button make sure you click there that you are targeting SQL Azure engine, therefore scroll down and find the script for the database engine type and in the drop down select SQL AZURE DATABASE.
Give the script a name and save it to a file and click next to generate the script file. Now that we have our script generated we can deploy the script to our destination SQL Azure database.
Now let's right-click on our SQL Azure database(MYCloudOki) in SSMS and select new query then open our generated saved script file and let execute the script against this query. once this is done then we should have the same schema from on-premises in MYCloudOki.
Step 2: Migrate data
Delete Using a delete to remove records, removes the records but remember the last primary key of the record deleted. This will allow the ne...
Building Database with MDA A maintenance-driven approach is better than tools-driven approach ; although with the tools-driven approach,...
Accessing ASP.NET Web Site Administration Tool Since the Membership Provider or ASP.NET Web Site Administration Tool that is used along w...
How to create default pictures slide advertisement Have you come across a web site where there are images moving on a slide? that might ...
Recursion Recursion is one of the most useful aspects of subroutines; that is the ability of the procedure or subroutine to call itsel...
How to Migrate SQL database to Azure Of course, it is very easy to build applications ruining on local computers and accessing stored d...
What is a List< T > A list is a type in .Net framework that holds generic types. Therefore List could store multiple items just l...
Understand String Manipulation String is an array of individual letters that we can loop through the string variable by accessing each ...
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 c...
Class and Object Object-Oriented Programming is easy when you understand the basis on how objects talk to each other to solve a given ...