sql >> Database teknologi >  >> RDS >> Sqlserver

SQL Server Tutorial – Alt hvad du behøver for at mestre Transact-SQL

I dagens marked, hvor en enorm mængde data bliver genereret hver dag, er det meget vigtigt at forstå, hvordan man håndterer data. SQL Server er et integreret miljø udviklet af Microsoft til at håndtere data. I denne artikel om SQL Server-selvstudiet lærer du alle de operationer og kommandoer, du skal bruge for at udforske dine databaser.

For din bedre forståelse har jeg opdelt bloggen i følgende kategorier:

Kommandoer Beskrivelse

Data Definition Language-kommandoer (DDL)

Dette sæt kommandoer bruges til at definere en database.

Sprogkommandoer for datamanipulation (DML)

Manipulationskommandoer bruges til at manipulere dataene i databasen.

Data Control Language-kommandoer (DCL)

Dette sæt kommandoer omhandler tilladelser, rettigheder og andre kontroller af databasesystemerne.

Transaction Control Language-kommandoer (TCL)

Disse kommandoer bruges til at håndtere transaktionen af ​​databasen.

Bortset fra kommandoerne er følgende emner dækket i denne artikel:

  1. Hvad er SQL Server?
  2. Installer SQL Server
  3. Opret forbindelse til SQL Server ved hjælp af SSMS
  4. Få adgang til databasemotor
  5. SQL-serverarkitektur
  6. Kommentarer i SQL
  7. SQL-serverdatatyper
  8. Nøgler i database
  9. Begrænsninger i databasen
  10. Operatører
  11. Aggregerede funktioner
  12. Brugerdefinerede funktioner
  13. Indlejrede forespørgsler
  14. Deltager
  15. løkker
  16. Lagrede procedurer
  17. Undtagelseshåndtering

***BEMÆRK*** I denne SQL Server Tutorial vil jeg overveje nedenstående database som et eksempel for at vise dig, hvordan du lærer og skriver kommandoer.

Student-ID StudentName Forældrenavn Telefonnummer Adresse By Land
1 Vihaan Akriti Mehra 9955339966 Brigade Road Block 9 Hyderabad Indien
2 Manasa Shourya Sharma 9234568762 Mayo Road 15 Kolkata Indien
3 Any Soumya Mishra 9876914261 Marathalli House No 101 Bengaluru Indien
4 Preeti Rohan Sinha 9765432234 Queens Road 40 Delhi Indien
5 Shanaya Abhinay Agarwal 9878969068 Oberoi Street 21 Mumbai Indien

Før vi begynder at forstå de forskellige kommandoer, der bruges i SQL Server, lad os forstå, hvad SQL Server er, dens arkitektur og hvordan den installeres.

Hvad er SQL Server?

Microsoft SQL Server er et relationelt databasestyringssystem. Det understøtter Structured Query-sproget og kommer med sin egen implementering af SQL-sproget, som er Transact-SQL(T-SQL) . Det har et integreret miljø til at håndtere SQL-databaser, som er SQL Server Management Studio.

Nøglekomponenterne i SQL Server er som følger:

  • Databasemotor: Denne komponent håndterer lagring, hurtig transaktionsbehandling og sikring af data.
  • SQL-server – Denne service bruges til at starte, stoppe, sætte på pause og fortsætte forekomsten af ​​MS SQL Server.
  • SQL Server Agent – ​​ Server Agent-tjenesten spiller rollen som opgaveplanlægger og udløses af enhver hændelse eller i henhold til kravet.
  • SQL-serverbrowser – Denne service bruges til at forbinde den indgående anmodning til den ønskede SQL Server-instans.
  • SQL Server fuldtekstsøgning – Bruges til at lade brugeren køre fuldtekstforespørgsler mod tegndataene i SQL-tabeller.
  • SQL Server VSS Writer Tillader sikkerhedskopiering og gendannelse af datafiler, når SQL Serveren ikke kører.
  • SQL Server Analysis Services (SSAS) – Denne service bruges til at levere dataanalyse, datamining og maskinlæring. SQL Serveren er også integreret med Python og R til avanceret dataanalyse.
  • SQL Server Reporting Services (SSRS) – Som navnet antyder, bruges denne tjeneste til at levere funktioner og beslutningstagningsmuligheder, herunder integration med Hadoop.
  • SQL Server Integration Services (SSIS) – Denne tjeneste bruges til at udføre ETL-operationer for forskellige typer data fra flere datakilder.

Nu, hvor du ved, hvad MS SQL Server er, så lad os gå videre i denne artikel om SQL Server-selvstudiet og forstå, hvordan man installerer og konfigurerer SQL Server.

Installer SQL Server

Følg nedenstående trin for at installere SQL Server:

Trin 1: Gå til den officielle side for Microsoft SQL Server download , hvor du finder muligheden for at installere SQL Server enten på stedet eller i skyen.

Trin 2: Rul nu ned, og du vil se to muligheder: Developer &Enterprise edition . Her vil jeg downloade Udviklerudgaven . For at downloade skal du blot klikke på Download nu mulighed. Se nedenfor.

Trin 3: Når applikationen er downloadet, skal du dobbeltklikke på filen, og du vil se følgende vindue.

Trin 4: Nu kan du vælge en af ​​de 3 muligheder for at konfigurere SQL Server. Her vil jeg bare vælge Grundlæggende mulighed . Ved valg af installationstype vil den næste skærm være at acceptere licensaftalen. For at gøre det skal du klikke på Accepter i det følgende vindue.

Trin 5: Dernæst skal du angive SQL Server-installationsplaceringen. Derefter skal du klikke på Installer.

Når du klikker på Installer , vil du se, at de nødvendige pakker bliver downloadet. Nu, efter installationen er fuldført, vil du se følgende skærmbillede:

Her kan du enten gå frem og klikke på Tilslut nu, eller du kan tilpasse installationen. For din bedre forståelse vil jeg gå videre og vælge Tilpas.

Trin 6: Når du klikker på Tilpas i ovenstående vindue vil du se følgende guide åbne. i det følgende vindue skal du klikke på Næste.

Trin 7: Når reglerne er installeret automatisk, skal du klikke på Næste . Se nedenfor.

Trin 8: Dernæst skal du vælge installationstype. Så vælg Udfør a ny installation af SQL Server 2017 og klik derefter påNæste.

Trin 9: I guiden, der åbnes, skal du vælge udgaven:Udvikler. Klik derefter på Næste . Se nedenfor.

Trin 10: Læs og accepter nu licensaftalerne ved at tjekke radioknappen ind og klik derefter på Næste . Se nedenfor.

Trin 11: I guiden nedenfor kan du vælge de funktioner, du ønsker at installere. Du kan også vælge forekomstens rodmappe og derefter klikke på Næste . Her vil jeg vælge Database Engine Services .

Trin 12: Dernæst skal du navngive instansen, og instans-id'et vil automatisk blive oprettet. Her vil jeg navngive forekomsten "edureka". Klik derefter på Næste.

Trin 13: Klik på Næste i guiden Serverkonfiguration .

Trin 14: Nu skal du aktivere godkendelsestilstandene. Her vil du se Windows-godkendelsestilstanden og Blandet tilstand . Jeg vil vælge blandet tilstand. Nævn derefter adgangskoden, og så tilføjer jeg den aktuelle bruger som Administrator ved at vælge Tilføj aktuel bruger mulighed.

Trin 15: Vælg derefter konfigurationsfilstien og klik på Installer .

Når installationen er fuldført, vil du se følgende skærmbillede:

Opret forbindelse til SQL Server ved hjælp af SSMS

Når SQL Serveren er installeret, er dit næste skridt at forbinde SQL Serveren til SQL Server Management Studio. For at gøre det skal du følge nedenstående trin:

Trin 1: Gå tilbage til det følgende vindue, og klik på installer SSMS mulighed.

Trin 2: Når du klikker på denne mulighed, vil du blive omdirigeret til den følgende side, hvor du skal vælge Download SSMS.

Trin 3: Når opsætningen er blevet downloadet, skal du dobbeltklikke på applikationen, og du vil se følgende guide åbne.

Trin 4: Klik på Installation , i ovenstående vindue, og du vil se, at installationen vil begynde.

Trin 5: Når installationen er fuldført, vil du få en dialogboks som vist nedenfor.

Når du har installeret SSMS'en, er næste trin at få adgang til databasemotoren .

Adgang til databasemotor

Når du åbner SQL-serveradministrationsstudiet fra startmenuen , åbnes et vindue svarende til vinduet vist på billedet nedenfor.

Nævn her servernavnet, godkendelsestilstanden og klik påOpret forbindelse.

Når du har klikket på Opret forbindelse , vil du se følgende skærmbillede.

Nå folkens, det er sådan du installerer og opsætter SQL Serveren. Lad os nu gå videre i denne SQL Server-øvelse, og lad os forstå de forskellige komponenter i SQL Server-arkitekturen.

SQL-serverarkitektur

SQL Servers arkitektur er som følger:

  • Server − Det er her SQL-tjenesterne er installeret og databasen ligger
  • Relationel motor − Indeholder forespørgselsparseren, optimeringsværktøjet og eksekveren; og udførelsen sker i den relationelle motor.
  • Kommando Parser − Kontrollerer forespørgslens syntaks og konverterer forespørgslen til maskinsprog.
  • Optimeringsværktøj − Forbereder udførelsesplanen som output ved at tage statistik, forespørgsel og algebratortræ som input.
  • Query Executor − Dette er stedet, hvor forespørgsler udføres trin for trin
  • Storage Engine − Denne er ansvarlig for opbevaring og genfinding af data på lagersystemet, manipulation af data, styring og låsning af transaktioner.

Nu, hvor du ved, hvordan du opsætter og installerer SQL Server og dens forskellige komponenter, så lad os komme i gang med at skrive kommandoer i SQL Server. Men før det, lad mig dække, hvordan man skriver kommentarer i SQL Server.

Kommentarer i SQL Server

Der er to måder, hvorpå du kan kommentere i SQL, dvs. enten bruge s kommentarer på én linje eller m ulti-line kommentarer .

Enkeltlinjekommentarer

Enkeltlinjekommentarerne starter med to bindestreger (–). Derfor vil teksten nævnt efter (–), indtil slutningen af ​​en enkelt linje blive ignoreret af compileren.

Eksempel:

--Example of single line comments

Multi-line kommentarer

Kommentarerne med flere linjer starter med /* og slutter med */ . Derfor er teksten nævnt mellem /* og */ vil blive ignoreret af compileren.

Eksempel:

/* Example for 
multi-line comments */

Lad os nu i denne artikel om SQL Server-selvstudiet starte med det første sæt kommandoer, dvs. Data Definition Language-kommandoer.

Data Definition Language-kommandoer

Dette afsnit af artiklen vil give dig en idé om de kommandoer, som du kan bruge til at definere din database. Kommandoerne er som følger:

  • OPRET
  • SLIP
  • ÆNDRING
  • TRUNCATE
  • OMDÆND

OPRET

Denne erklæring bruges til at oprette en tabel, database eller visning.

'CREATE DATABASE'-erklæringen

Denne erklæring bruges til at oprette en database.

Syntaks

CREATE DATABASE DatabaseName;

Eksempel

CREATE DATABASE Students;

'OPRET TABEL'-erklæringen

Som navnet antyder, bruges denne erklæring til at oprette en tabel.

Syntaks

CREATE TABLE TableName (
Column1 datatype,
Column2 datatype,
Column3 datatype,
....

ColumnN datatype
);

Eksempel

CREATE TABLE StudentInfo
(
StudentID int,
StudentName varchar(8000),
ParentName varchar(8000),
PhoneNumber int,
AddressofStudent varchar(8000),
City varchar(8000),
Country varchar(8000)
);

SLIP

Denne erklæring bruges til at slette en eksisterende tabel, database eller visning.

'DROP DATABASE'-erklæringen

Denne erklæring bruges til at slette en eksisterende database. Den komplette information, der findes i databasen, vil gå tabt, så snart du udfører kommandoen nedenfor.

Syntaks

DROP DATABASE DatabaseName;

Eksempel

DROP DATABASE Students;

'Drop TABEL'-erklæringen

Denne sætning bruges til at slette en eksisterende tabel. Den komplette information i tabellen vil gå tabt, så snart du udfører kommandoen nedenfor.

Syntaks

DROP TABLE TableName;

Eksempel

DROP TABLE StudentInfo;

ÆNDRING

ALTER-kommandoen bruges til at tilføje, slette eller ændre kolonner eller begrænsninger i en eksisterende tabel.

'ÆNDRINGSTABEL'-erklæringen

Denne erklæring bruges til at tilføje, slette, ændre kolonner i en allerede eksisterende tabel.

'ÆNDRINGSTABEL'-erklæringen med TILFØJ/SLIP-KOLONNE

ALTER TABLE-sætningen bruges med ADD/DROP Column-kommandoen til at tilføje og slette en kolonne.

Syntaks

ALTER TABLE TableName
ADD ColumnName Datatype;

ALTER TABLE TableName
DROP COLUMN ColumnName;

Eksempel

--ADD Column BloodGroup:
ALTER TABLE StudentInfo
ADD BloodGroup varchar(8000);
 
--DROP Column BloodGroup:
ALTER TABLE StudentInfo
DROP COLUMN BloodGroup ;

'ÆNDRINGSTABEL'-erklæringen med ÆNDRINGSKOLUMN

ALTER TABLE-sætningen kan bruges sammen med ALTER-kolonnen til at ændre datatypen for en eksisterende kolonne i en tabel.

Syntaks

ALTER TABLE TableName
ALTER COLUMN ColumnName Datatype;

Eksempel

--Add a column DOB and change the data type from date to datetime.
ALTER TABLE StudentInfo
ADD DOB date;
ALTER TABLE StudentInfo
ALTER COLUMN DOB datetime;

TRUNCATE

Denne SQL-kommando bruges til at slette oplysningerne i tabellen, men sletter ikke selve tabellen. Så hvis du vil slette oplysningerne i tabellen, og ikke slette selve tabellen, skal du bruge TRUNCATE-kommandoen. Ellers skal du bruge DROP-kommandoen.

Syntaks

TRUNCATE TABLE TableName;

Eksempel

TRUNCATE TABLE StudentInfo;

OMDØB

Denne erklæring bruges til at omdøbe en eller flere tabeller.

Syntaks

sp_rename 'OldTableName', 'NewTableName';

Eksempel

sp_rename 'StudentInfo', 'Infostudents';

Vi går videre i denne artikel om SQL Server-selvstudiet, og lad os forstå de forskellige datatyper, der understøttes af SQL Server.

SQL-serverdatatyper

Datatypekategori Datatypenavn Beskrivelse Range/syntaks
Nøjagtige tal numerisk Bruges til at gemme numeriske værdier og have faste præcisions- og skaleringsnumre – 10^38 +1 til 10^38 – 1.
tinyint Bruges til at gemme heltalsværdier 0 til 255
smallint Bruges til at gemme heltalsværdier -2^15 (-32.768) til 2^15-1 (32.767)
bigint Bruges til at gemme heltalsværdier -2^63 (-9,223,372,036,854,775,808) til 2^63-1 (9,223,372,036,854,775,807)
int Bruges til at gemme heltalsværdier -2^31 (-2.147.483.648) til 2^31-1 (2.147.483.647)
bit Gemmer en heltalsdatatype med en værdi på 0, 1 eller NULL 0, 1 eller NULL
decimal Bruges til at gemme numeriske værdier og have faste præcisions- og skaleringsnumre – 10^38 +1 til 10^38 – 1.
småpenge Bruges til at gemme penge- eller valutaværdier. – 214.748.3648 til 214.748.3647
penge Bruges til at gemme penge- eller valutaværdier. -922,337,203,685,477,5808 til 922,337,203,685,477,5807 (-922,337,203,685,477,58
til 922.337.203.685.477,58 for Informatica.
Omtrentlig tal float Bruges til at gemme numeriske flydende kommadata – 1.79E+308 til -2.23E-308, 0 og 2.23E-308 til 1.79E+308
rigtig Bruges til at gemme numeriske flydende kommadata – 3.40E + 38 til -1.18E – 38, 0 og 1.18E – 38 til 3.40E + 38
Dato og tid dato Bruges til at definere en dato i SQL Server. Syntaks:dato
smalldatetime Bruges til at definere en dato, der er kombineret med et tidspunkt på dagen; hvor tiden er baseret på en 24-timers dag, med sekunder altid nul (:00) og uden brøkdele af sekunder. Syntaks:smalldatetime
datotid Bruges til at definere en dato, der er kombineret med et tidspunkt på dagen med brøkdele af sekunder baseret på et 24-timers ur. Syntaks:datetime
datetime2 datetime2 er som en forlængelse af den eksisterende datotid type, der har en større standard brøkpræcision, større datointerval. Syntaks:datetime2
datotidsforskydning Bruges til at definere en dato, der er kombineret med et klokkeslæt på dagen, der har tidszonebevidsthed. Den er baseret på et 24-timers ur. Syntaks:datetimeoffset
tid Bruges til at definere et tidspunkt på dagen. Syntaks:tid
Tegnstrenge char Bruges til at gemme tegn i fast størrelse. char [ ( n ) ] hvor n-værdien varierer fra 1 – 8.000
varchar Bruges til at gemme tegn med variabel længde. varchar [ ( n | max ) ] hvor n-værdien varierer fra 1-8000 og den maksimalt tilladte lagerplads er 2 GB.
tekst Bruges til at gemme ikke-Unicode-data med variabel længde Maksimal strenglængde tilladt – 2^31-1 (2.147.483.647)
Unicode-tegnstrenge nchar Bruges til at gemme tegn i fast størrelse. nchar [ ( n ) ] hvor n-værdien varierer fra 1-4000
nvarchar Bruges til at gemme tegn med variabel længde. varchar [ ( n | max ) ] hvor n-værdien varierer fra 1-4000 og den maksimalt tilladte lagerplads er 2 GB.
ntekst Bruges til at gemme Unicode-data med variabel længde Maksimal strenglængde tilladt – 2^30-1 (2.147.483.647)
Binære strenge binær Bruges til at gemme binære datatyper af enten fast længde binær [ ( n ) ] hvor n-værdien varierer fra 1 – 8.000
variabel Bruges til at gemme binære datatyper af enten fast længde varbinær [ ( n ) ] hvor n-værdien varierer fra 1-8000 og den maksimalt tilladte lagring er 2^31-1 bytes.
billede Bruges til at gemme binære data med variabel længde 0 – 2^31-1 (2.147.483.647) bytes
Andre datatyper markør Det er en datatype for lagrede procedurer eller variable OUTPUT-parametre, der indeholder en reference til en markør.
rowversion Bruges til at afsløre automatisk genererede, unikke binære tal i en database.
hierarchyid Bruges til at repræsentere position i et hierarki.
uniqueidentifier Er en 16-byte GUID. Syntaks:unik identifikator
sql_variant Bruges til at gemme værdierne for forskellige SQL Server-understøttede datatyper Syntaks:sql_variant
xml Bruges til at gemme XML-datatype.

xml ( [ INDHOLD | DOKUMENT ] xml_skemasamling )

typer af rumlig geometri Bruges til at repræsentere data i et euklidisk (fladt) koordinatsystem.
typer af rumlig geografi Bruges til at gemme ellipseformede (runde-jorden) data, såsom GPS-bredde- og længdegradskoordinater.
tabel Bruges til at gemme et resultatsæt til behandling på et senere tidspunkt

Lad os derefter i denne artikel forstå de forskellige typer nøgler og begrænsninger i databasen.

Forskellige typer nøgler i databasen

Følgende er de forskellige typer nøgler, der bruges i databasen:

  • Kandidatnøgle – Kandidatnøgle er et sæt attributter, der unikt kan identificere en tabel. En tabel kan have mere end en enkelt kandidatnøgle, og ud af de valgte kandidatnøgler vælges én nøgle som den primære nøgle.
  • Supernøgle – Sættet af attributter kan entydigt identificere en tupel. Så kandidatnøgler, unikke nøgler og primærnøgler er supernøgler, men det omvendte er ikke sandt.
  • Primær nøgle – Primære nøgler bruges til entydigt at identificere hver tupel.
  • Alternativ nøgle – Alternative nøgler er de kandidatnøgler, der ikke er valgt som en primær nøgle.
  • Unik nøgle – Unikke nøgler ligner den primære nøgle, men tillader en enkelt NULL-værdi i kolonnen.
  • Udenlandsk nøgle – En attribut, der kun kan tage de tilstedeværende værdier som værdierne af en anden attribut, er fremmednøglen til den attribut, som den refererer til.
  • Sammensat nøgle – Sammensatte nøgler er en kombination af to eller flere kolonner, der identificerer hver tupel unikt.

Begrænsninger brugt i databasen

Begrænsninger bruges i en database til at specificere reglerne for data gemt i en tabel. De forskellige typer begrænsninger i SQL er som følger:

  • IKKE NULL
  • UNIKT
  • TJEK
  • STANDARD
  • INDEX

NOT NULL

The NOT NULL constraint ensures that a column cannot have a NULL value.

Example

CREATE TABLE StudentsInfo
(
StudentID int NOT NULL,
StudentName varchar(8000) NOT NULL,
ParentName varchar(8000),
PhoneNumber int ,
AddressofStudent varchar(8000) NOT NULL,
City varchar(8000),
Country varchar(8000)
);

--NOT NULL on ALTER TABLE
ALTER TABLE StudentsInfo
ALTER COLUMN PhoneNumber int NOT NULL;

UNIQUE

This constraint ensures that all the values in a column are unique.

Example

--UNIQUE on Create Table
 
CREATE TABLE StudentsInfo
(
StudentID int NOT NULL UNIQUE,
StudentName varchar(8000) NOT NULL,
ParentName varchar(8000),
PhoneNumber int ,
AddressofStudent varchar(8000) NOT NULL,
City varchar(8000),
Country varchar(8000)
);
 
--UNIQUE on Multiple Columns
 
CREATE TABLE StudentsInfo
(
StudentID int NOT NULL,
StudentName varchar(8000) NOT NULL,
ParentName varchar(8000),
PhoneNumber int ,
AddressofStudent varchar(8000) NOT NULL,
City varchar(8000),
Country varchar(8000)
CONSTRAINT UC_Student_Info UNIQUE(StudentID, PhoneNumber)
);
 
--UNIQUE on ALTER TABLE
 
ALTER TABLE StudentsInfo
ADD UNIQUE (StudentID);
 
--To drop a UNIQUE constraint
 
ALTER TABLE  StudentsInfo
DROP CONSTRAINT UC_Student_Info;

CHECK

The CHECK constraint ensures that all the values in a column satisfy a specific condition.

Example

--CHECK Constraint on CREATE TABLE
 
CREATE TABLE StudentsInfo
(
StudentID int NOT NULL,
StudentName varchar(8000) NOT NULL,
ParentName varchar(8000),
PhoneNumber int ,
AddressofStudent varchar(8000) NOT NULL,
City varchar(8000),
Country varchar(8000) CHECK (Country ='India')
);
 
--CHECK Constraint on multiple columns
 
CREATE TABLE StudentsInfo
(
StudentID int NOT NULL,
StudentName varchar8000) NOT NULL,
ParentName varchar(8000),
PhoneNumber int ,
AddressofStudent varchar(8000) NOT NULL,
City varchar(8000),
Country varchar(8000) CHECK (Country ='India'  AND City = 'Hyderabad')
);
 
--CHECK Constraint on ALTER TABLE
 
ALTER TABLE StudentsInfo
ADD CHECK (Country ='India');
 
--To give a name to the CHECK Constraint
 
ALTER TABLE StudentsInfo
ADD CONSTRAINT CheckConstraintName CHECK (Country ='India');
 
--To drop a CHECK Constraint
 
ALTER TABLE StudentsInfo
DROP CONSTRAINT CheckConstraintName;

DEFAULT

The DEFAULT constraint consists of a set of default values for a column when no value is specified.

Example

--DEFAULT Constraint on CREATE TABLE
 
CREATE TABLE StudentsInfo
(
StudentID int,
StudentName varchar(8000) NOT NULL,
ParentName varchar(8000),
PhoneNumber int ,
AddressofStudent varchar(8000) NOT NULL,
City varchar(8000),
Country varchar(8000) DEFAULT 'India'
);
 
--DEFAULT Constraint on ALTER TABLE
 
ALTER TABLE StudentsInfo
ADD CONSTRAINT defau_Country
DEFAULT 'India' FOR Country;
 
--To drop the Default Constraint
 
ALTER TABLE StudentsInfo
ALTER COLUMN Country DROP defau_Country;

INDEX

The INDEX constraint is used to create indexes in the table, through which you can create and retrieve data from the database very quickly.

Syntax

--Create an Index where duplicate values are allowed
CREATE INDEX IndexName
ON TableName (Column1, Column2, ...ColumnN);

--Create an Index where duplicate values are not allowed
CREATE UNIQUE INDEX IndexName
ON TableName (Column1, Column2, ...ColumnN);

Example

CREATE INDEX idex_StudentName
ON StudentsInfo (StudentName);
 
--To delete an index in a table
 DROP INDEX StudentsInfo.idex_StudentName;

Moving forward in this article on SQL Server tutorial, let us now understand the different Data Manipulation Language commands used in Microsoft SQL Server.

Data Manipulation Language commands

This section of the article will cover all those commands through which you can manipulate the database. The commands are as follows:

  • USE
  • INSERT INTO
  • UPDATE
  • SLET
  • MERGE
  • SELECT
  • CUBE
  • ROLLUP
  • OFFSET
  • FETCH
  • TOP
  • PIVOT

Apart from these commands, there are also other manipulative operators/functions such as:

  • Operators
    • Arithmetic Operators
    • Assignment Operators
    • Bitwise Operators
    • Comparison Operators
    • Compound Operators
    • Logical Operators
    • Scope Resolution Operators
    • Set Operators
    • String Concatenation Operators
    • Aggregate Functions
  • User-Defined Functions

USE

This statement is used to select the database to start performing various operations on it.

Syntax

USE DatabaseName;

Example

USE Students;

INSERT INTO

The INSERT INTO statement is used to insert new records into an existing table.

Syntax

INSERT INTO TableName (Column1, Column2, Column3, ...,ColumnN)
VALUES (value1, value2, value3, ...);

--If you don't want to mention the column names then use the below syntax

INSERT INTO TableName
VALUES (Value1, Value2, Value3, ...);

Example

INSERT INTO StudentsInfo(StudentID, StudentName, ParentName, PhoneNumber, AddressofStudent, City, Country)
VALUES ('06', 'Sanjana','Kapoor', '9977331199', 'Buffalo Street House No 10', 'Kolkata', 'India');
 
INSERT INTO StudentsInfo
VALUES ('07', 'Vishal','Mishra', '9876509712', 'Nice Road 15', 'Pune', 'India');

OPDATERING

The UPDATE statement is used to modify or update the records already present in the table.

Syntax

UPDATE TableName
SET Column1 = Value1, Column2 = Value2, ...
WHERE Condition;

Example

UPDATE StudentsInfo
SET StudentName = 'Aahana', City= 'Ahmedabad'
WHERE StudentID = 1;

DELETE

The DELETE statement is used to delete the existing records in a table.

Syntax

DELETE FROM TableName WHERE Condition;

Example

DELETE FROM StudentsInfo
WHERE StudentName='Aahana';

MERGE

The MERGE statement is used to perform the INSERT, UPDATE and DELETE operations on a specific table, where the source table is provided. Se nedenfor.

Syntax

MERGE TagretTableName USING SourceTableName
ON MergeCondition
WHEN MATCHED
THEN Update_Statement
WHEN NOT MATCHED
THEN Insert_Statement
WHEN NOT MATCHED BY SOURCE
THEN DELETE;

Example

To understand the MERGE statement, consider the following tables as the Source table and the Target table.

Source Table:

Student-ID StudentName Marks
1 Vihaan 87
2 Manasa 92
4 Anay 74

Target Table:

Student-ID StudentName Marks
1 Vihaan 87
2 Manasa 67
3 Saurabh 55
MERGE SampleTargetTable TARGET USING SampleSourceTable SOURCE ON (TARGET.StudentID = SOURCE.StudentID)                                                                                       
WHEN MATCHED AND TARGET.StudentName <> SOURCE.StudentName OR TARGET.Marks <> SOURCE.Marks 
THEN UPDATE SET TARGET.StudentName = SOURCE.StudentName, TARGET.Marks = SOURCE.Marks         
WHEN NOT MATCHED BY TARGET THEN  
INSERT (StudentID,StudentName,Marks) VALUES (SOURCE.StudentID,SOURCE.StudentName,SOURCE.Marks)
WHEN NOT MATCHED BY SOURCE THEN         
DELETE;    

Output

StudentID StudentName Marks
1 Vihaan 87
2 Manasa 92
4 Anay 74

SELECT

The SELECT statement is used to select data from a database, table or view. The data returned is stored in a result table, called the result-set .

Syntax

SELECT Column1, Column2, ...ColumN
FROM TableName;

--(*) is used to select all from the table
SELECT * FROM table_name;

-- To select the number of records to return use:
SELECT TOP 3 * FROM TableName;

Example

-- To select few columns
SELECT StudentID, StudentName
FROM StudentsInfo;
 
--(*) is used to select all from the table
SELECT * FROM StudentsInfo;
 
-- To select the number of records to return use:
SELECT TOP 3 * FROM StudentsInfo;

We can also use the following keywords with the SELECT statement:

  • DISTINCT
  • ORDER BY
  • GROUP BY
  • GROUPING SETS
  • HAVING Clause
  • INTO

DISTINCT

The DISTINCT keyword is used with the SELECT statement to return only different values.

Syntax

SELECT DISTINCT Column1, Column2, ...ColumnN
FROM TableName;

Example

SELECT DISTINCT PhoneNumber FROM StudentsInfo;

ORDER BY

This statement is used to sort the required results either in the ascending or descending order. By default, the results are stored in ascending order. Yet, if you wish to get the results in descending order, you have to use the DESC søgeord.

Syntax

SELECT Column1, Column2, ...ColumnN
FROM TableName
ORDER BY Column1, Column2, ... ASC|DESC;

Example

-- Select all students from the 'StudentsInfo' table sorted by ParentName:
SELECT * FROM StudentsInfo
ORDER BY ParentName;
 
-- Select all students from the 'StudentsInfo' table sorted by ParentName in Descending order:
SELECT * FROM StudentsInfo
ORDER BY ParentName DESC;
 
-- Select all students from the 'StudentsInfo' table sorted by ParentName and StudentName:
SELECT * FROM StudentsInfo
ORDER BY ParentName, StudentName;

/* Select all students from the 'StudentsInfo' table sorted by ParentName 
in Descending order and StudentName in Ascending order: */
SELECT * FROM StudentsInfo
ORDER BY ParentName ASC, StudentName DESC;

GROUP BY

This statement is used with the aggregate functions to group the result-set by one or more columns.

Syntax

SELECT Column1, Column2,..., ColumnN
FROM TableName
WHERE Condition
GROUP BY ColumnName(s)
ORDER BY ColumnName(s);

Example

-- To list the number of students from each city.
SELECT COUNT(StudentID), City
FROM StudentsInfo
GROUP BY City;

GROUPING SETS

GROUPING SETS were introduced in SQL Server 2008, used to generate a result-set that can be generated by a UNION ALL of the multiple simple GROUP BY clauses.

Syntax

SELECT ColumnNames(s)
FROM TableName
GROUP BY GROUPING SETS(ColumnName(s));

Example

SELECT StudentID, StudentName, COUNT(City)
from StudentsInfo
Group BY
GROUPING SETS
((StudentID, StudentName, City),(StudentID),(StudentName),(City));

HAVING

This clause is used in the scenario where the WHERE keyword cannot be used.

Syntax

SELECT ColumnName(s)
FROM TableName
WHERE Condition
GROUP BY ColumnName(s)
HAVING Condition
ORDER BY ColumnName(s);

Example

SELECT COUNT(StudentID), City
FROM StudentsInfo
GROUP BY City
HAVING COUNT(StudentID) > 2
ORDER BY COUNT(StudentID) DESC;

INTO

The INTO keyword can be used with the SELECT statement to copy data from one table to another. Well, you can understand these tables to be temporary tables. The temporary tables are generally used to perform manipulations on data present in the table, without disturbing the original table.

Syntax

SELECT *
INTO NewTable [IN ExternalDB]
FROM OldTable
WHERE Condition;

Example

-- To create a backup of table 'StudentsInfo'
SELECT * INTO StudentsBackup
FROM StudentsInfo;
 
--To select only few columns from StudentsInfo
SELECT StudentName, PhoneNumber INTO StudentsDetails
FROM StudentsInfo;
 
SELECT * INTO PuneStudents
FROM StudentsInfo
WHERE City = 'Pune';

CUBE

CUBE is an extension of the GROUP BY clause. It allows you to generate the sub-totals for all the combinations of the grouping columns specified in the GROUP BY clause.

Syntax

SELECT ColumnName(s)
FROM TableName
GROUP BY CUBE(ColumnName1, ColumnName2, ....., ColumnNameN);

Example

SELECT StudentID, COUNT(City)
FROM StudentsInfo
GROUP BY CUBE(StudentID)
ORDER BY StudentID;  

ROLLUP

ROLLUP is an extension of the GROUP BY clause. This allows you to include the extra rows which represent the subtotals. These are referred to as super-aggregated rows along with the grand total row.

Syntax

SELECT ColumnName(s)
FROM TableName
GROUP BY ROLLUP(ColumnName1, ColumnName2, ....., ColumnNameN);

Example

SELECT StudentID, COUNT(City)
FROM StudentsInfo
GROUP BY ROLLUP(StudentID);

OFFSET

The OFFSET clause is used with the SELECT and ORDER BY statement to retrieve a range of records. It must be used with the ORDER BY clause since it cannot be used on its own. Also, the range that you mention must be equal to or greater than 0. If you mention a negative value, then it shows an error.

Syntax

SELECT ColumnNames)
FROM TableName
WHERE Condition
ORDER BY ColumnName(s)
OFFSET RowsToSkip ROWS;

Example

Consider a new column Marks in the StudentsInfo tabel.

SELECT StudentName, ParentName
FROM StudentsInfo
ORDER BY Marks
OFFSET 1 ROWS;

FETCH

The FETCH clause is used to return a set of a number of rows. It has to be used in conjunction with the OFFSET clause.

Syntax

SELECT ColumnNames)
FROM TableName
WHERE Condition
ORDER BY ColumnName(s)
OFFSET RowsToSkip 
FETCH NEXT NumberOfRows ROWS ONLY;

Example

SELECT StudentName, ParentName
FROM StudentsInfo
ORDER BY Marks
OFFSET 1 ROWS
FETCH  NEXT 1 ROWS ONLY;

TOP

The TOP clause is used with the SELECT statement to mention the number of records to return.

Syntax

SELECT TOP Number ColumnName(s)
FROM TableName
WHERE Condition;

Example

SELECT TOP 3 * FROM StudentsInfo;

PIVOT

PIVOT is used to rotate the rows to column values and runs aggregations when required on the remaining column values.

Syntax

SELECT NonPivoted ColumnName,  
    [First Pivoted ColumnName] AS ColumnName,  
    [Second Pivoted ColumnName] AS ColumnName, 
    [Third Pivoted ColumnName] AS ColumnName,   
    ...  
    [Last Pivoted ColumnName] AS ColumnName  
FROM 
    (SELECT query which produces the data)   
    AS [alias for the initial query]  
PIVOT  
(  
    [AggregationFunction](ColumName)  
FOR  
[ColumnName of the column whose values will become column headers]   
    IN ( [First Pivoted ColumnName], [Second Pivoted ColumnName],  [Third Pivoted ColumnName]
    ... [last pivoted column])  
) AS [alias for the Pivot Table];

Example

To get a detailed example, you can refer to my article on SQL PIVOT and UNPIVOT. Next in this SQL Server Tutorial let us look into the different operators supported by Microsoft SQL Server.

Operators

The different types of operators supported by SQL Server are as follows:

  • Arithmetic Operators
  • Assignment Operators
  • Bitwise Operators
  • Comparison Operators
  • Compound Operators
  • Logical Operators
  • Scope Resolution Operators
  • Set Operators
  • String Concatenation Operators

Let us discuss each one of them one by one.

Arithmetic Operators

Operator Meaning Syntax

+

Addition

expression + expression

Subtraction

expression – expression

*

Multiplication

expression * expression

/

Divison

expression / expression

%

Modulous

expression % expression

Assignment Operators

Operator Meaning Syntax

=

Assign a value to a variable

variable =‘value’

Bitwise Operators

Operator Meaning Syntax

&(Bitwise AND)

Used to perform a bitwise logical AND operation between two integer values.

expression &expression

&=(Bitwise AND Assignment)

Used to perform a bitwise logical AND operation between two integer values. It also sets a value to the output of the operation.

expression &=expression

| (Bitwise OR)

Used to perform a bitwise logical OR operation between two integer values as translated to binary expressions within Transact-SQL statements.

expression | expression

|=(Bitwise OR Assignment)

Used to perform a bitwise logical OR operation between two integer values as translated to binary expressions within Transact-SQL statements. It also sets a value to the output of the operation.

expression |=expression

^ (Bitwise Exclusive OR)

Used to perform a bitwise exclusive OR operation between two integer values.

expression ^ expression

^=(Bitwise Exclusive OR Assignment)

Used to perform a bitwise exclusive OR operation between two integer values. It also sets a value to the output of the operation.

expression ^=expression

~ (Bitwise NOT)

Used to perform a bitwise logical NOT operation on an integer value.

~ expression

Comparison Operators

Operator Meaning Syntax

=

Equal to

expression =expression

>

Greater than

expression> expression

<

Less than

expression

>=

Greater than or equal to

expression>=expression

<=

Less than or equal to

expression <=expression

<>

Not equal to

expression <> expression

!=

Not equal to

expression !=expression

!<

Not less than

expression !

!>

Not greater than

expression !> expression

Compound Operators

Operator Meaning Syntax

+ =

Used to add value to the original value and set the original value to the result.

expression +=expression

-=

Used to subtract a value from the original value and set the original value to the result.

expression -=expression

*=

Used to multiply value to the original value and set the original value to the result.

expression *=expression

/=

Used to divide a value from the original value and set the original value to the result.

expression /=expression

%=

Used to divide a value from the original value and set the original value to the result.

expression %=expression

&=

Used to perform a bitwise AND operation and set the original value to the result.

expression &=expression

^=

Used to perform a bitwise exclusive OR operation and set the original value to the result.

expression ^=expression

|=

Used to perform a bitwise OR operation and set the original value to the result.

expression |=expression

Logical Operators

Operator Meaning Syntax

ALL

Returns TRUE if all of set of comparisons are TRUE.

scalar_expression { =| <> | !=|> |>=| !> | <| <=| !<} ALL ( subquery )

AND

Returns TRUE if both the expressions are TRUE.

boolean_expression AND boolean_expression

ANY

Returns TRUE if any one of a set of comparisons are TRUE.

scalar_expression { =| <> | ! =|> |> =| !> | <| <=| ! <} { ANY } ( subquery )

BETWEEN

Returns TRUE if an operand is within a range.

sampleexpression [ NOT ] BETWEEN beginexpression AND endexpression

EXISTS

Returns TRUE if a subquery contains any rows.

EXISTS (sub query)

IN

Returns TRUE if an operand is equal to one of a list of expressions.

test_expression [ NOT ] IN( subquery | expression [ ,…n ])

LIKE

Returns TRUE if an operand matches a pattern.

match_expression [ NOT ] LIKE pattern [ ESCAPE escape_character ]

NOT

Reverses the value of any boolean operator.

[ NOT ] boolean_expression

OR

Returns TRUE if either of the boolean expression is TRUE.

boolean_expression OR boolean_expression

SOME

Returns TRUE if some of a set of comparisons are TRUE.

scalar_expression { =| <> | ! =|> |> =| !> | <| <=| ! <} { SOME} ( subquery )

Scope Resolution Operators

Operator Meaning Example

::

Provides access to static members of a compound data type. Compound data types are those data types which contain multiple methods and simple data types. Compound data types These include the built-in CLR types and custom SQLCLR User-Defined Types (UDTs).

DECLARE @hid hierarchyid; SELECT @hid =hierarchyid::GetRoot(); PRINT @hid.ToString();

Set Operators

There are mainly three set operations:UNION, INTERSECT, MINUS. You can refer to the image below to understand the set operations in SQL. Refer to the below image:

Operator Meaning Syntax

UNION

The UNION operator is used to combine the result-set of two or more SELECT statements.

SELECT ColumnName(s) FROM Table1
UNION
SELECT ColumnName(s )FROM Table2;

INTERSECT

The INTERSECT clause is used to combine two SELECT statements and return the intersection of the data-sets of both the SELECT statements.

SELECT Column1 , Column2 ….
FROM TableName;
WHERE Condition
INTERSECT
SELECT Column1 , Column2 ….
FROM TableName;
WHERE Condition

EXCEPT

The EXCEPT operator returns those tuples that are returned by the first SELECT operation, and are not returned by the second SELECT operation.

SELECT ColumnName
FROM TableName;
EXCEPT
SELECT ColumnName
FROM TableName;

String Operators

Operator Meaning Syntax/ Example

+ (String Concatenation)

Concatenates two or more binary or character strings, columns, or a combination of strings and column names into a single expression

expression+expression

+=(String Concatenation)

Used to concatenate two strings and sets the string to the result of the operation.

expression+=expression

% (Wildcard Characters to match)

Used to matches any string of zero or more characters.

Example:‘sample%’

[] (Wildcard Characters to match)

Used to match a single character within the specified range or set that is specified between brackets [].

Example:m[n-z]%’

[^] (Wildcard Characters to match)

Used to match a single character which is not within the range or set specified between the square brackets.

Example:‘Al[^a]%’

_ (Wildcard Characters to match)

Used to match a single character in a string comparison operation

test_expression [ NOT ] IN( subquery | expression [ ,…n ])

Aggregate Functions

The different aggregate functions supported by SQL Server are as follows:

Function Description Syntax Example

SUM()

Used to return the sum of a group of values.

SELECT SUM(ColumnName) FROM TableName;

SELECT SUM(Marks) FROM StudentsInfo;

COUNT()

Returns the number of rows either based on a condition, or without a condition.

SELECT COUNT(ColumnName) FROM TableName WHERE Condition;

SELECT COUNT(StudentID) FROM StudentsInfo;

AVG()

Used to calculate the average value of a numeric column.

SELECT AVG(ColumnName) FROM TableName;

SELECT AVG(Marks) FROM StudentsInfo;

MIN()

This function returns the minimum value of a column.

SELECT MIN(ColumnName) FROM TableName;

SELECT MIN(Marks) FROM StudentsInfo;

MAX()

Returns a maximum value of a column.

SELECT MAX(ColumnName) FROM TableName;

SELECT MAX(Marks) FROM StudentsInfo;

FIRST()

Used to return the first value of the column.

SELECT FIRST(ColumnName) FROM TableName;

SELECT FIRST(Marks) FROM StudentsInfo;

LAST()

This function returns the last value of the column.

SELECT LAST(ColumnName) FROM TableName;

SELECT LAST(Marks) FROM StudentsInfo;

User-Defined Functions

Microsoft SQL Server allows the users to create user-defined functions which are routines. These routines accept parameters, can perform simple to complex actions and return the result of that particular action as a value. Here, the value returned can either be a single scalar value or a complete result-set.

You can use user-defined functions to:

  • Allow modular programming
  • Reduce network traffic
  • Allow faster execution of queries

Also, there are different types of user-defined functions you can create. De er:

  • Scalar Functions: Used to return a single data value of the type defined in the RETURNS clause.
  • Table-Valued Functions: Used to return a table data type.
  • System Functions: A variety of system functions are provided by the SQL Server to perform different operations.

Well, apart from the user-defined functions, there is a bunch of in-built functions in SQL Server; which can be used to perform a variety of tasks. Moving on in this article on SQL Server tutorial, let us now understand what are nested queries.

Nested Queries

Nested queries are those queries that have an outer query and inner subquery. So, basically, the subquery is a query which is nested within another query such as SELECT, INSERT, UPDATE or DELETE. Refer to the image below:

Next in this SQL Server tutorial, let us understand the different types of joins in SQL.

Joins

Joins are used to combine tuples from two or more tables, based on a related column between the tables. There are four types of joins:

  • INNER JOIN: Returns records that have matching values in both the tables.
  • LEFT JOIN: Returns records from the left table, and also those records which satisfy the condition from the right table.
  • RIGHT JOIN: Returns records from the right table, and also those records which satisfy the condition from the left table.
  • FULL JOIN: Returns records which either have a match in the left or the right table.

Consider the following table along with the StudentsInfo table, to understand the syntax of joins.

SubjectID StudentID SubjectName
10 10 Maths
2 11 Physics
3 12 Chemistry

INNER JOIN

Syntax

SELECT ColumnName(s)
FROM Table1
INNER JOIN Table2 ON Table1.ColumnName = Table2.ColumnName;

Example

SELECT Subjects.SubjectID, StudentsInfo.StudentName
FROM Subjects
INNER JOIN StudentsInfo ON Subjects.StudentID = StudentsInfo.StudentID;

LEFT JOIN

Syntax

SELECT ColumnName(s)
FROM Table1
LEFT JOIN Table2 ON Table1.ColumnName = Table2.ColumnName;

Example

SELECT StudentsInfo.StudentName, Subjects.SubjectID
FROM StudentsInfo
LEFT JOIN Subjects ON StudentsInfo.SubjectID = Subjects.SubjectID
ORDER BY StudentsInfo.StudentName;

RIGHT JOIN

Syntax

SELECT ColumnName(s)
FROM Table1
RIGHT JOIN Table2 ON Table1.ColumnName = Table2.ColumnName;

Example

SELECT StudentsInfo.StudentName, Subjects.SubjectID
FROM StudentsInfo
RIGHT JOIN Subjects ON StudentsInfo.SubjectID = Subjects.SubjectID
ORDER BY StudentsInfo.StudentName;

FULL JOIN

Syntax

SELECT ColumnName(s)
FROM Table1
FULL OUTER JOIN Table2 ON Table1.ColumnName = Table2.ColumnName;

Example

SELECT StudentsInfo.StudentName, Subjects.SubjectID
FROM StudentsInfo
FULL OUTER JOIN Subjects ON StudentsInfo.SubjectID = Subjects.SubjectID
ORDER BY StudentsInfo.StudentName;

Next, in this article on SQL Server tutorial, let us understand the different types of loops supported by the SQL Server.

Loops

The different control-of-flow commands are as follows:

  • BEGIN..END
  • BREAK
  • CONTINUE
  • GOTO
  • IF..ELSE
  • RETURN
  • WAITFOR
  • WHILE

Let us discuss each one of them one by one.

BEGIN..END

These keywords are used to enclose a series of SQL statements. Then, this group of SQL statements can be executed.

Syntax

BEGIN   
     { SQLStatement | StatementBlock }   
END

BREAK

This statement is used to exit the current WHILE loop. In case, the current WHILE loop is nested inside another loop, then the BREAK statement exits only the current loop and the control is passed on to the next statement in the current loop. The BREAK statement is generally used inside an IF statement.

Syntax

BREAK;

CONTINUE

The CONTINUE statement is used to restart a WHILE loop. So, any statements after the CONTINUE keyword will be ignored.

Syntax

CONTINUE;

Here, Label is the point after which processing starts if a GOTO is targeted to that particular label.

GOTO

Used to alter the flow of execution to a label. The statements written after the GOTO keyword are skipped and processing continues at the label.

Syntax

Define Label:   
Label:   
Alter Execution:  
GOTO Label

Here, Label is the point after which processing starts if a GOTO is targeted to that particular label.

IF..ELSE

Like any other programming language, the If-else statement in SQL Server tests the condition and if the condition is false then ‘else’ statement is executed.

Syntax

IF BooleanExpression      
     { SQLStatement | StatementBlock }   
[ ELSE   
     { SQLStatement | StatementBlock } ]

RETURN

Used to exit unconditionally from a query or procedure. So, the statements which are written after the RETURN clause are not executed.

Syntax

RETURN [ IntegerExpression ]

Here, an integer value is returned.

WAITFOR

The WAITFOR control flow is used to block the execution of a stored procedure, transaction or a batch until a specific statement modifies, returns at least one row or a specified time or time interval elapses.

Syntax

WAITFOR   
{  
    DELAY 'TimeToPass'   
  | TIME 'TimeToExecute'   
  | [ ( RecieveStatement ) | ( GetConversionGroupStatement ) ]   
    [ , TIMEOUT timeout ]  
}

where,

  • DELAY – Period of time that must pass
  • TimeToPass – Period of time to wait
  • TIME – The time when the stored procedure, transaction or the batch runs.
  • TimeToExecute – The time at which the WAITFOR statement finishes.
  • RecieveStatement – A valid RECEIVE statement.
  • GetConversionGroupStatement – A valid GET CONVERSATION GROUP statement.
  • TIMEOUT timeout Specifies the period of time, in milliseconds, to wait for a message to arrive on the queue.

WHILE

This loop is used to set a condition for repeated execution of a particular SQL statement or a SQL statement block. The statements are executed as long as the condition mentioned by the user is TRUE. As soon as the condition fails, the loop stops executing.

Syntax

WHILE BooleanExpression 
{ SQLStatement | StatementBlock | BREAK | CONTINUE }

Now, that you guys know the DML commands, let’s move onto our next section in this article on SQL Tutorial i.e. the DCL commands.

Data Control Language Commands (DCL)

This section of SQL Server tutorial will give you an idea about the command through which are used to enforce database security in multiple user database environments. The commands are as follows:

  • GRANT
  • REVOKE

GRANT

The GRANT command is used to provide access or privileges on the database and its objects to the users.

Syntax

GRANT PrivilegeName
ON ObjectName
TO {UserName |PUBLIC |RoleName}
[WITH GRANT OPTION];

where,

  • PrivilegeName – Is the privilege/right/access granted to the user.
  • ObjectName – Name of a database object like TABLE/VIEW/STORED PROC.
  • UserName – Name of the user who is given the access/rights/privileges.
  • PUBLIC – To grant access rights to all users.
  • RoleName – The name of a set of privileges grouped together.
  • WITH GRANT OPTION – To give the user access to grant other users with rights.

Example

-- To grant SELECT permission to StudentsInfo table to user1
GRANT SELECT ON StudentsInfo TO user1;

REVOKE

The REVOKE command is used to withdraw the user’s access privileges given by using the GRANT command.

Syntax

REVOKE PrivilegeName 
ON ObjectName 
FROM {UserName |PUBLIC |RoleName}

Example

-- To revoke the granted permission from user1
REVOKE SELECT ON StudentsInfo TO user1;

Moving on in this SQL Server tutorial, let us understand the how to create and use Stored Procedures.

Stored Procedures

Stored Procedures are reusable units that encapsulate a specific business logic of the application. So, it is a group of SQL statements and logic, compiled and stored together to perform a specific task.

Syntax

CREATE [ OR REPLACE] PROCEDURE procedure_name [
(parameter_name [IN | OUT | IN OUT] type [ ])]
{IS | AS }
BEGIN [declaration_section]
executable_section 
//SQL statement used in the stored procedure
END
GO

Example

--Create a procedure that will return a student name when the StudentId is given as the input parameter to the stored procedure
Create  PROCEDURE GetStudentName 
(
@StudentId INT, --Input parameter ,  
@StudName VARCHAR(50)  OUT  --Output parameter, 
AS
BEGIN
SELECT @StudName = StudentName FROM StudentsInfo WHERE StudentID=@StudentId
END

Steps to execute:

      • Declare @StudName as nvarchar(50)
      • EXEC GetStudentName 01, @StudName output
      • SELECT @StudName

The above procedure returns the name of a particular student, on giving that students id as input. Next in this SQL Server tutorial, let us understand the transaction control language commands.

Transaction Control Language Commands (TCL)

This section of SQL Server tutorial will give you an insight into the commands which are used to manage transactions in the database. The commands are as follows:

  • COMMIT
  • ROLLBACK
  • SAVEPOINT

COMMIT

The COMMIT command is used to save the transaction into the database.

Syntax

COMMIT;

ROLLBACK

The ROLLBACK command is used to restore the database to the last committed state.

Syntax

ROLLBACK;

BEMÆRK: When you use ROLLBACK with SAVEPOINT, then you can directly jump to a savepoint in an ongoing transaction. Syntax:ROLLBACK TO SavepointName;

SAVEPOINT

The SAVEPOINT command is used to temporarily save a transaction. So if you wish to rollback to any point, then you can save that point as a ‘SAVEPOINT’.

Syntax

SAVEPOINT SAVEPOINTNAME;

Consider the below table to understand the working of transactions in the database.

StudentID StudentName
1 Rohit
2 Suhana
3 Ashish
4 Prerna

Now, use the below SQL queries to understand the transactions in the database.

INSERT INTO StudentTable VALUES(5, 'Avinash');
COMMIT;
UPDATE StudentTable SET name = 'Akash' WHERE id = '5';
SAVEPOINT S1;
INSERT INTO StudentTable VALUES(6, 'Sanjana');
SAVEPOINT S2;
INSERT INTO StudentTable VALUES(7, 'Sanjay');
SAVEPOINT S3;
INSERT INTO StudentTable VALUES(8, 'Veena');
SAVEPOINT S4;
SELECT * FROM StudentTable;

Next in this article on SQL Server tutorial let us understand how to handle exceptions in Transact-SQL.

Exception Handling

There are two types of exceptions, i.e, the system-defined exceptions and the user-defined exceptions. As the name suggests, exception handling is a process through which a user can handle the exceptions generated. To handle exceptions you have to understand the following control flow statements:

  • THROW
  • TRY…CATCH

THROW

This clause is used to raise an exception and transfers the execution to a CATCH block of a TRY…CATCH construct.

Syntax

THROW [ { ErrorNumber | @localvariable },  
        { Message | @localvariable },  
        { State | @localvariable } ]   
[ ; ]

where,

  • ErrorNumber – A constant or variable that represents the exception.
  • Message – A variable or string that describes the exception.
  • State – A constant or variable between 0 and 255 that indicates the state to associate with the message.
THROW 51000, 'Record does not exist.', 1;  

TRY..CATCH

Used to implement exception handling in Transact-SQL. A group of statements can be enclosed in the TRY block. In case an error occurs in the TRY block, control is passed to another group of statements that are enclosed in a CATCH block.

Syntax

BEGIN TRY  
     { SQLStatement | StatementBlock}  
END TRY  
BEGIN CATCH  
     [ { SQLStatement | StatementBlock } ]  
END CATCH  
[ ; ]
BEGIN TRY  
    SELECT * FROM StudentsInfo;  
END TRY  
BEGIN CATCH  
    SELECT   
        ERROR_NUMBER() AS ErNum , ERROR_MESSAGE() AS ErMsg;  
END CATCH

W ith this, we come to the end of this article on SQL Server Tutorial. I hope you enjoyed reading this article on SQL Server Tutorial For Beginners. I f you wish to get a structured training on MySQL, then check out our MySQL DBA Certification Training som kommer med instruktørledet livetræning og projekterfaring i det virkelige liv. Denne træning vil hjælpe dig med at forstå MySQL i dybden og hjælpe dig med at opnå beherskelse over emnet. Har du et spørgsmål til os? Please mention it in the comments section of ”SQL Server Tutorial ” og jeg vender tilbage til dig.


  1. En sammenligning mellem MySQL Clone Plugin og Xtrabackup

  2. Sådan installeres Oracle SQL Developer 18.2 på Windows 10?

  3. Opsætning af fremmednøgle med anden datatype

  4. Nye metadata-kun kolonneændringer i SQL Server 2016