Difference between Delete and Truncate


Using a delete to remove records, removes the records but remember the last primary key of the record deleted.
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?


Using a truncate to remove records, removes the records but never remember the last primary key of the record deleted. 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


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

Date offsets

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 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.


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

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

Maxybyte Program

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

Maxybyte Program

The following select statement can also be used.
select @firstname + coalesce('  '  + @middlename, ") +  '  ' + @lastname as 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
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, 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


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


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

occupation_code SMALLINT NOT NULL,
address VARCHAR(255) 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.

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
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.
SELECT hotel_nr
FROM Reservation
GROUP BY 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
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.

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
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, 
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.


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.


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".


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.


UPDATE Reservation_backup 
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' 
(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:


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. 


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 in C#


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.
Tower of Hanoi
Diagram Tower of Hanoi 
The rules of this puzzle are:

  1. We are interested in moving the rings from A to B, perhaps using  C in the process. 
  2. Also by the rules of the game, rings are to be moved one at a time
  3.  At no point may the larger ring be placed on top a smaller one.
This puzzle can be solved following these 7 steps:
  • 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;


subroutine move N from A to B using C;
  1. if N is 1 then print "move A to B";
  2. else( If N is greater than 1) do the following:                 
            2.1 call move N - 1 from  A to C using B;
            2.2 call  move 1   from A to B using  C;
            2.3 call move N - 1 from  C to B using A;
    3. return


 We have 3 rings on Peg A, therefore, our N = 3, which is greater than 1.
 After the function; below are the 3 Steps our code follows:
 P(3, A, C, B) means  call move 3 from A to B using C
 Step1: P(N - 1, Beg, End, Aux)  
 Step2: P(1,       Beg,  Aux, End)
 Step3: P(N - 1, Aux, Beg, End)

 Below also are the meaning of the variables selected:

 P = denotes procedure/subroutine
 N = numbers of ring
 Beg = Initial stage of moving the ring
 End = destination 
 Aux = auxiliary output through which we move rings

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.

Let us see in code:
namespace TowerOfHanoi
class Program
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_fromPegdest_Pegvia_PegtoDest);
solverHanoiTowers(1, beg_fromPegvia_PegtoDest, dest_Peg);
solverHanoiTowers(n - 1, via_PegtoDest, beg_fromPegdest_Peg);



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;

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.

Happy reading! 
Follow maxybyte on social media.

Read: Class and Object -Object-Oriented Programming

Database with Maintenance-Driven Approach

Building Database with MDA

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.

Step1: Create a project-LocalDbMDA
Then rename this project to LocalDbMDA.Presentation, This layer present the end result of the application to the end user.
LocalDbMDA.Presentation Diagram
Step2: Adding New Projects to the Main Project
Ideally, It is good to make the Persistence and the Presentation layers depend on the Domain
Now we need to add the 2 other layers the domain and the persistence layers by selecting from the menu for each new project.  File > Add > New Projects. Moreover, right within the new project Dialogue, choose Class Library, and be sure that the selection for the solution is changed to 'Add to Solution' and not 'Create New Solution'.
 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.

Step3: Set Dependencies through Add References
Ideally, you do not want your project to depend on each other, which is the main principle of SOC. But some level of dependency is going to be needed. A project taking dependency from another one simply means a project makes reference to another one in code. Now the Reference logic that we will use for this lesson looks like this:
                      Reference                 Reference
Presentation -------------->Domain--------------> Persistence

layer, which will keep the dependency chain central to the Domain layer, like this:

                      Reference                      Reference
Presentation ---------------->Domain<--------------Persistence

Re-create the Entity Model in the Persistence Layer and also add Data Transfer Object that each layer will reference. This DTO allows data transfers access within the other 3 layers.

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".

You can also check out an environment for executing SQL statements based on different SQL DBMSs and a set of SQL puzzles
You can also check these catalogs of data models, that contain logical design models of SQL databases. These help us to understand databases domains and hence are an important source of information for the creation of conceptual data models.

Migrate SQL database to Azure SQL database

How to Migrate SQL database to Azure 

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.

The benefit of using Azure is because of its scalability, availability, tenancy, provisioning, and their payment model. I will give you the simple logic on how you can construct and transfer your database from your local computer and access it online instead.

SQL Server Management Studio(SSMS) will be useful for this tutorial, it is free, you can directly get it from Microsoft.

Follow the instructions and install it.
Then we will need to follow two steps for this migration:

  • Schema migration from the on-premises database to SQL Azure
  • Table data migration from the on-premises database to SQL Azure
Now to start migration; open SSMS  and connect to a Database engine for our local SQL express instance but also you can connect to a SQL Server on the server on your network, since we presently have the database built in our computer, then connect to the Local SQL express instance.
Database LocalDB
Database LocalDB Diagram
Step 1: Once you are connected, expand the "Databases" to see what you have there
Right inside after expansion, choose the database you want to move, in my case I will use my database named OKIDOKI_7b18cd1fa3f4, then I expand the Tables and have this diagram below that you can follow:
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

Once that is done you can access it from SSMS by connecting to the sever name you used during the time you created the sever in the Azure portal mine looks migratingsql.database.windows.net and in Authentication space in SSMS  select SQL sever Authentication.

Maxybyte SQL Server
 SQL Server Diagram

Enter your connection information and click the connect button. Then once you log in right-click Databases and choose new database OR click on Databases to highlight it and click on new query , right inside the new query we can create and name our database to be in the cloud.
Copy and paste this code to create the database named MYCloudOki:


And click the Execute button in SSMS.
If you follow tutorial correctly then you should have a new Azure database name MyCloudOki that we will use for our destination.
As I mentioned there are 2 steps to the migration we start with migrating our database schema and we will migrate our data.

To migrate our schema from on-premises to Azure database destination, we will right_click on the

Maxybyte Generate scripts
Generate scripts Diagram
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
Now we need to move the Data, there are numbers of options available to move the data, such as:
-SQL server integration services, -BCP , - sqlBulkCopy. 

In this case, we will use the SSIS package to move the data. We are going to use SSMS To run the wizard and create an SSIS package.

Now let's right-click on our source database OKIDOKI_7b18cd1fa3f4 go to Tasks and select Export data , then from the wizard specified the source database and the destination database which is in SQL Azure therefore choose.Net framework data provider for SQL server, then scroll down a little and enter the credentials for our destination database and click next and run it immediately. Once the migration is done you can run a query to make sure the data is there. 

Happy coding...

Your feedback will help others...

New Post

Difference between Delete and Truncate

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...