sql >> Base de Datos >  >> RDS >> Sqlserver

Tutorial de SQL Server:todo lo que necesita para dominar Transact-SQL

En el mercado actual, donde se genera una enorme cantidad de datos todos los días, es muy importante entender cómo manejarlos. SQL Server es un entorno integrado desarrollado por Microsoft para manejar datos. En este artículo sobre el tutorial de SQL Server, aprenderá todas las operaciones y comandos que necesita para explorar sus bases de datos.

Para su mejor comprensión, he dividido el blog en las siguientes categorías:

Comandos Descripción

Comandos del lenguaje de definición de datos (DDL)

Este conjunto de comandos se utilizan para definir una base de datos.

Comandos del lenguaje de manipulación de datos (DML)

Los comandos de manipulación se utilizan para manipular los datos presentes en la base de datos.

Comandos del lenguaje de control de datos (DCL)

Este conjunto de comandos se ocupa de los permisos, derechos y otros controles de los sistemas de bases de datos.

Comandos del lenguaje de control de transacciones (TCL)

Estos comandos se utilizan para gestionar la transacción de la base de datos.

Además de los comandos, en este artículo se tratan los siguientes temas:

  1. ¿Qué es SQL Server?
  2. Instalar servidor SQL
  3. Conéctese a SQL Server usando SSMS
  4. Motor de base de datos de acceso
  5. Arquitectura del servidor SQL
  6. Comentarios en SQL
  7. Tipos de datos del servidor SQL
  8. Claves en la base de datos
  9. Restricciones en la base de datos
  10. Operadores
  11. Funciones agregadas
  12. Funciones definidas por el usuario
  13. Consultas anidadas
  14. Únete
  15. Bucles
  16. Procedimientos almacenados
  17. Manejo de excepciones

***NOTA*** En este tutorial de SQL Server, consideraré la siguiente base de datos como ejemplo, para mostrarle cómo aprender y escribir comandos.

Id. de estudiante Nombre del estudiante Nombre principal Número de teléfono Dirección Ciudad País
1 Vihaan Akriti Mehra 9955339966 Bloque de carreteras de la brigada 9 Hyderabad India
2 Manasa Shourya Sharma 9234568762 Carretera Mayo 15 Calcuta India
3 Análisis Soumya Mishra 9876914261 Casa Marathalli nº 101 Bengalore India
4 Preeti Rohan Sinha 9765432234 Queens Road 40 Delhi India
5 Shanaya Abhinay Agarwal 9878969068 Calle Oberoi 21 Bombay India

Antes de comenzar a comprender los diferentes comandos utilizados en SQL Server, comprendamos qué es SQL Server, su arquitectura y cómo instalarlo.

¿Qué es SQL Server?

Microsoft SQL Server es un sistema de administración de bases de datos relacionales. Es compatible con el lenguaje de consultas estructuradas y viene con su propia implementación del lenguaje SQL, que es el Transact-SQL(T-SQL) . Tiene un entorno integrado para manejar bases de datos SQL, que es SQL Server Management Studio.

Los componentes clave de SQL Server son los siguientes:

  • Motor de base de datos: Este componente maneja el almacenamiento, el procesamiento rápido de transacciones y la protección de datos.
  • Servidor SQL – Este servicio se utiliza para iniciar, detener, pausar y continuar la instancia de MS SQL Server.
  • Agente SQL Server – El servicio Server Agent desempeña el papel de programador de tareas y se activa por cualquier evento o según el requisito.
  • Explorador de SQL Server – Este servicio se utiliza para conectar la solicitud entrante a la instancia de SQL Server deseada.
  • Búsqueda de texto completo de SQL Server: Se utiliza para permitir que el usuario ejecute consultas de texto completo en los datos de caracteres en tablas SQL.
  • Escritor VSS de SQL Server Permite copias de seguridad y restauración de archivos de datos cuando SQL Server no se ejecuta.
  • Servicios de análisis de SQL Server (SSAS) – Este servicio se utiliza para proporcionar capacidades de análisis de datos, extracción de datos y aprendizaje automático. SQL Server también está integrado con Python y R para análisis de datos avanzados.
  • Servicios de informes de SQL Server (SSRS) – Como sugiere el nombre, este servicio se utiliza para proporcionar funciones y capacidades de toma de decisiones, incluida la integración con Hadoop.
  • Servicios de integración de SQL Server (SSIS) – Este servicio se utiliza para realizar operaciones ETL para diferentes tipos de datos de múltiples fuentes de datos.

Ahora que sabe qué es MS SQL Server, avancemos en este artículo sobre el tutorial de SQL Server y comprendamos cómo instalar y configurar SQL Server.

Instalar servidor SQL

Siga los pasos a continuación para instalar SQL Server:

Paso 1: Vaya a la página oficial de descarga de Microsoft SQL Server , donde encontrará la opción de instalar SQL Server de forma local o en la nube.

Paso 2: Ahora, desplácese hacia abajo y verá dos opciones: Edición para desarrolladores y empresas . Aquí, descargaré la edición para desarrolladores . Para descargar, solo tienes que hacer clic en el botón Descargar ahora opción. Consulte a continuación.

Paso 3: Una vez descargada la aplicación, haga doble clic en el archivo y verá la siguiente ventana.

Paso 4: Ahora, puede elegir cualquiera de las 3 opciones para configurar SQL Server. Aquí, solo elegiré la opción básica . Al seleccionar la opción de tipo de instalación, la siguiente pantalla sería aceptar el acuerdo de licencia. Para ello, haga clic en Aceptar en la siguiente ventana.

Paso 5: A continuación, debe especificar la ubicación de instalación de SQL Server. Luego, debe hacer clic en Instalar.

Una vez que haga clic en Instalar , verá que se están descargando los paquetes necesarios. Ahora, una vez completada la instalación, verá la siguiente pantalla:

Aquí, puede avanzar y hacer clic en Conectar ahora, o puede personalizar la instalación. Para su mejor comprensión, continuaré y elegiré Personalizar.

Paso 6: Una vez que haga clic en Personalizar en la ventana de arriba, verá que se abre el siguiente asistente. en la siguiente ventana, haga clic en Siguiente.

Paso 7: Después de que las reglas se instalen automáticamente, haga clic en Siguiente . Consulte a continuación.

Paso 8: A continuación, debe elegir el tipo de instalación. Por lo tanto, elija Realizar un nueva instalación de SQL Server 2017 opción y luego haga clic en Siguiente.

Paso 9: En el asistente que se abre, elija la edición:Desarrollador. Luego, haga clic en Siguiente . Consulte a continuación.

Paso 10: Ahora, lea y acepte los acuerdos de licencia marcando el botón de radio y luego haga clic en Siguiente . Consulte a continuación.

Paso 11: En el siguiente asistente, puede elegir las funciones que desea instalar. Además, puede elegir el directorio raíz de la instancia y luego hacer clic en Siguiente . Aquí, elegiré los Servicios del motor de base de datos .

Paso 12: A continuación, debe nombrar la instancia y automáticamente se creará la ID de la instancia. Aquí, nombraré la instancia "edureka". Luego, haga clic en Siguiente.

Paso 13: En el asistente de configuración del servidor, haga clic en Siguiente .

Paso 14: Ahora, debe habilitar los modos de autenticación. Aquí verá el modo de autenticación de Windows y modo mixto . Elegiré el modo mixto. Luego, mencione la contraseña y luego agregaré al usuario actual como Administrador eligiendo Agregar usuario actual opción.

Paso 15: Luego, elija la ruta del archivo de configuración y haga clic en Instalar .

Una vez completada la instalación, verá la siguiente pantalla:

Conéctese a SQL Server usando SSMS

Después de instalar SQL Server, el siguiente paso es conectar SQL Server a SQL Server Management Studio. Para hacerlo, siga los pasos a continuación:

Paso 1: Regrese a la siguiente ventana y haga clic en instalar SSMS opción.

Paso 2: Una vez que haga clic en esa opción, será redirigido a la siguiente página, donde debe elegir Descargar SSMS.

Paso 3: Una vez descargada la configuración, haga doble clic en la aplicación y verá que se abre el siguiente asistente.

Paso 4: Haga clic en Opción de instalación , en la ventana de arriba y verás que comenzará esa instalación.

Paso 5: Una vez completada la instalación, obtendrá un cuadro de diálogo como se muestra a continuación.

Después de instalar el SSMS, el siguiente paso es acceder al Motor de base de datos .

Acceso al motor de base de datos

Cuando abre el estudio de administración del servidor SQL desde el menú de inicio , se abrirá una ventana similar a la ventana que se muestra en la imagen a continuación.

Aquí, mencione el nombre del servidor, el modo de autenticación y haga clic en Conectar.

Después de hacer clic en Conectar , verá la siguiente pantalla.

Bueno, amigos, así es como instalan y configuran SQL Server. Ahora, avanzando en este tutorial de SQL Server, comprendamos los diferentes componentes de la arquitectura de SQL Server.

Arquitectura de servidor SQL

La arquitectura de SQL Server es la siguiente:

  • Servidor − Aquí es donde se instalan los servicios SQL y reside la base de datos
  • Motor relacional − Contiene el analizador de consultas, el optimizador y el ejecutor; y la ejecución ocurre en el motor relacional.
  • Analizador de comandos − Comprueba la sintaxis de la consulta y convierte la consulta a lenguaje de máquina.
  • Optimizador − Prepara el plan de ejecución como salida tomando estadísticas, consulta y árbol de Algebrator como entrada.
  • Ejecutor de consultas − Este es el lugar donde las consultas se ejecutan paso a paso
  • Motor de almacenamiento − Este es responsable del almacenamiento y recuperación de datos en el sistema de almacenamiento, manipulación de datos, gestión y bloqueo de transacciones.

Ahora que sabe cómo configurar e instalar SQL Server y sus diversos componentes, comencemos a escribir comandos en SQL Server. Pero, antes de eso, permítanme explicar cómo escribir comentarios en SQL Server.

Comentarios en SQL Server

Hay dos formas de comentar en SQL, es decir, usar las s comentarios de una sola línea o la m comentarios de última línea .

Comentarios de una sola línea

Los comentarios de una sola línea comienzan con dos guiones (–). Por lo tanto, el compilador ignorará el texto mencionado después de (–), hasta el final de una sola línea.

Ejemplo:

--Example of single line comments

Comentarios de varias líneas

Los comentarios de varias líneas comienzan con /* y terminan con */ . Por lo tanto, el texto mencionado entre /* y */ será ignorado por el compilador.

Ejemplo:

/* Example for 
multi-line comments */

Ahora, en este artículo sobre el tutorial de SQL Server, comencemos con el primer conjunto de comandos, es decir, los comandos del lenguaje de definición de datos.

Comandos del lenguaje de definición de datos

Esta sección del artículo le dará una idea sobre los comandos con la ayuda de los cuales puede definir su base de datos. Los comandos son los siguientes:

  • CREAR
  • SOLTAR
  • ALTERAR
  • TRUNCADO
  • CAMBIAR NOMBRE

CREAR

Esta declaración se usa para crear una tabla, base de datos o vista.

La declaración 'CREAR BASE DE DATOS'

Esta declaración se usa para crear una base de datos.

Sintaxis

CREATE DATABASE DatabaseName;

Ejemplo

CREATE DATABASE Students;

La declaración 'CREATE TABLE'

Como sugiere el nombre, esta declaración se usa para crear una tabla.

Sintaxis

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

ColumnN datatype
);

Ejemplo

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

SOLTAR

Esta declaración se usa para descartar una tabla, base de datos o vista existente.

Declaración 'DROP DATABASE'

Esta declaración se usa para descartar una base de datos existente. La información completa presente en la base de datos se perderá tan pronto como ejecute el siguiente comando.

Sintaxis

DROP DATABASE DatabaseName;

Ejemplo

DROP DATABASE Students;

La declaración 'DROP TABLE'

Esta instrucción se usa para descartar una tabla existente. La información completa presente en la tabla se perderá tan pronto como ejecute el siguiente comando.

Sintaxis

DROP TABLE TableName;

Ejemplo

DROP TABLE StudentInfo;

CAMBIAR

El comando ALTER se usa para agregar, eliminar o modificar columnas o restricciones en una tabla existente.

La declaración 'ALTER TABLE'

Esta declaración se usa para agregar, eliminar y modificar columnas en una tabla preexistente.

La declaración 'ALTER TABLE' con ADD/DROP COLUMN

La declaración ALTER TABLE se usa con el comando ADD/DROP Column para agregar y eliminar una columna.

Sintaxis

ALTER TABLE TableName
ADD ColumnName Datatype;

ALTER TABLE TableName
DROP COLUMN ColumnName;

Ejemplo

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

La declaración 'ALTER TABLE' con ALTER COLUMN

La declaración ALTER TABLE se puede usar con la columna ALTER para cambiar el tipo de datos de una columna existente en una tabla.

Sintaxis

ALTER TABLE TableName
ALTER COLUMN ColumnName Datatype;

Ejemplo

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

TRUNCADO

Este comando SQL se usa para eliminar la información presente en la tabla, pero no elimina la tabla en sí. Entonces, si desea eliminar la información presente en la tabla y no eliminar la tabla en sí, debe usar el comando TRUNCATE. De lo contrario, use el comando DROP.

Sintaxis

TRUNCATE TABLE TableName;

Ejemplo

TRUNCATE TABLE StudentInfo;

CAMBIAR NOMBRE

Esta declaración se usa para cambiar el nombre de una o más tablas.

Sintaxis

sp_rename 'OldTableName', 'NewTableName';

Ejemplo

sp_rename 'StudentInfo', 'Infostudents';

Continuando con este artículo sobre el tutorial de SQL Server, comprendamos los diferentes tipos de datos admitidos por SQL Server.

Tipos de datos de SQL Server

Categoría de tipo de datos Nombre del tipo de datos Descripción Rango/ Sintaxis
Números exactos numérico Se utiliza para almacenar valores numéricos y tener números de escala y precisión fijos – 10^38 +1 a 10^38 – 1.
tinyint Usado para almacenar valores enteros 0 a 255
smallint Usado para almacenar valores enteros -2^15 (-32,768) a 2^15-1 (32,767)
bigint Usado para almacenar valores enteros -2^63 (-9,223,372,036,854,775,808) a 2^63-1 (9,223,372,036,854,775,807)
int Usado para almacenar valores enteros -2^31 (-2,147,483,648) a 2^31-1 (2,147,483,647)
bit Almacena un tipo de dato entero que cuenta con un valor de 0, 1 o NULL 0, 1 o NULL
decimal Se utiliza para almacenar valores numéricos y tener números de escala y precisión fijos – 10^38 +1 a 10^38 – 1.
dinero pequeño Se utiliza para almacenar valores monetarios o de divisas. – 214.748,3648 a 214.748,3647
dinero Se utiliza para almacenar valores monetarios o de divisas. -922,337,203,685,477.5808 a 922,337,203,685,477.5807 (-922,337,203,685,477.58
al 922.337.203.685.477,58 para Informática.
Números aproximados flotante Usado para almacenar datos numéricos de coma flotante – 1,79E+308 a -2,23E-308, 0 y 2,23E-308 a 1,79E+308
real Usado para almacenar datos numéricos de coma flotante – 3,40E + 38 a -1,18E – 38, 0 y 1,18E – 38 a 3,40E + 38
Fecha y hora fecha Usado para definir una fecha en SQL Server. Sintaxis:fecha
smalldatetime Se utiliza para definir una fecha que se combina con una hora del día; donde la hora se basa en un día de 24 horas, con segundos siempre cero (:00) y sin fracciones de segundo. Sintaxis:smalldatetime
datetime Se utiliza para definir una fecha que se combina con una hora del día con segundos fraccionarios basados ​​en un reloj de 24 horas. Sintaxis:fecha y hora
datetime2 datetime2 es como una extensión del datetime existente tipo que tiene una mayor precisión fraccionaria predeterminada, mayor rango de fechas. Sintaxis:datetime2
datetimeoffset Se utiliza para definir una fecha que se combina con una hora del día que tiene reconocimiento de zona horaria. Se basa en un reloj de 24 horas. Sintaxis:datetimeoffset
tiempo Se utiliza para definir una hora del día. Sintaxis:tiempo
Cadenas de caracteres char Se utiliza para almacenar caracteres de tamaño fijo. char [ ( n ) ] donde el valor de n varía de 1 a 8000
varchar Se utiliza para almacenar caracteres de longitud variable. varchar [ ( n | max ) ] donde el valor de n varía de 1 a 8000 y el almacenamiento máximo permitido es de 2 GB.
texto Se utiliza para almacenar datos no Unicode de longitud variable Longitud de cadena máxima permitida:2^31-1 (2,147,483,647)
Cadenas de caracteres Unicode nchar Se utiliza para almacenar caracteres de tamaño fijo. nchar [ ( n ) ] donde el valor de n varía de 1 a 4000
nvarchar Se utiliza para almacenar caracteres de longitud variable. varchar [ ( n | max ) ] donde el valor de n varía de 1 a 4000 y el almacenamiento máximo permitido es de 2 GB.
ntext Se utiliza para almacenar datos Unicode de longitud variable Longitud de cadena máxima permitida:2^30-1 (2,147,483,647)
Cadenas binarias binario Se utiliza para almacenar tipos de datos binarios de longitud fija binary [ ( n ) ] donde el valor de n varía de 1 a 8000
varbinary Se utiliza para almacenar tipos de datos binarios de longitud fija varbinary [ ( n ) ] donde el valor de n varía de 1 a 8000 y el almacenamiento máximo permitido es de 2^31-1 bytes.
imagen Usado para almacenar datos binarios de longitud variable 0 – 2^31-1 (2,147,483,647) bytes
Otros tipos de datos cursor Es un tipo de datos para procedimientos almacenados o parámetros de SALIDA de variables que contienen una referencia a un cursor.
rowversion Se utiliza para exponer números binarios únicos generados automáticamente dentro de una base de datos.
hierarchyid Se utiliza para representar la posición en una jerarquía.
identificador único Es un GUID de 16 bytes. Sintaxis:identificador único
sql_variant Se utiliza para almacenar los valores de varios tipos de datos compatibles con SQL Server Sintaxis:sql_variant
xml Utilizado para almacenar tipo de datos XML.

xml ( [ CONTENIDO | DOCUMENTO ] xml_schemacollection )

Tipos de geometría espacial Se utiliza para representar datos en un sistema de coordenadas euclidiano (plano).
Tipos de geografía espacial Se utiliza para almacenar datos elipsoidales (tierra redonda), como las coordenadas de latitud y longitud del GPS.
tabla Se utiliza para almacenar un conjunto de resultados para su procesamiento posterior

A continuación, en este artículo, comprendamos los diferentes tipos de claves y restricciones en la base de datos.

Diferentes tipos de claves en la base de datos

Los siguientes son los diferentes tipos de claves utilizadas en la base de datos:

  • Clave de candidato: La clave candidata es un conjunto de atributos que pueden identificar de forma única una tabla. Una tabla puede tener más de una sola clave candidata y, de las claves candidatas elegidas, se elige una clave como clave principal.
  • Supertecla – El conjunto de atributos puede identificar de forma única una tupla. Por lo tanto, las claves candidatas, las claves únicas y las claves primarias son superclaves, pero lo contrario no es cierto.
  • Primary Key – Primary keys are used to uniquely identify every tuple.
  • Alternate Key – Alternate Keys are those candidate keys that are not chosen as a Primary key.
  • Unique Key – Unique keys are similar to the primary key, but allow a single NULL value in the column.
  • Foreign Key – An attribute that can only take the values present as the values of some other attribute, is the foreign key to the attribute to which it refers.
  • Composite Key – Composite keys are a combination of two or more columns that identify each tuple uniquely.

Constraints Used In Database

Constraints are used in a database to specify the rules for data stored in a table. The different types of constraints in SQL are as follows:

  • NOT NULL
  • UNIQUE
  • CHECK
  • DEFAULT
  • 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
  • ELIMINAR
  • 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');

ACTUALIZAR

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. Consulte a continuación.

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:

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

Target Table:

StudentID 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 palabra clave.

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

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. Consulte la siguiente imagen:

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. They are:

  • 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;

NOTA: 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 que viene con capacitación en vivo dirigida por un instructor y experiencia en proyectos de la vida real. This training will help you understand MySQL in-depth and help you achieve mastery over the subject. Got a question for us? Please mention it in the comments section of ”SQL Server Tutorial ” and I will get back to you.