Di pasar saat ini, di mana sejumlah besar data dihasilkan setiap hari, sangat penting untuk memahami cara menangani data. SQL Server adalah lingkungan terintegrasi yang dikembangkan oleh Microsoft untuk menangani data. Dalam artikel tentang tutorial SQL Server ini, Anda akan mempelajari semua operasi dan perintah yang Anda perlukan untuk menjelajahi database Anda.
Untuk pemahaman Anda yang lebih baik, saya telah membagi blog ke dalam kategori berikut:
Perintah | Deskripsi |
Perintah Bahasa Definisi Data (DDL) | Serangkaian perintah ini digunakan untuk mendefinisikan database. |
Perintah Bahasa Manipulasi Data (DML) | Perintah manipulasi digunakan untuk memanipulasi data yang ada dalam database. |
Perintah Bahasa Kontrol Data (DCL) | Serangkaian perintah ini berhubungan dengan izin, hak, dan kontrol lain dari sistem database. |
Perintah Bahasa Kontrol Transaksi (TCL) | Perintah ini digunakan untuk menangani transaksi database. |
Selain perintah, topik berikut dibahas dalam artikel ini:
- Apa itu SQL Server?
- Instal SQL Server
- Hubungkan ke SQL Server menggunakan SSMS
- Akses Mesin Basis Data
- Arsitektur SQL Server
- Komentar dalam SQL
- Tipe Data SQL Server
- Kunci dalam database
- Batasan dalam basis data
- Operator
- Fungsi Agregat
- Fungsi Buatan Pengguna
- Kueri Bertingkat
- Bergabung
- Pengulangan
- Prosedur Tersimpan
- Penanganan Pengecualian
***CATATAN*** Dalam Tutorial SQL Server ini, saya akan mempertimbangkan database di bawah ini sebagai contoh, untuk menunjukkan kepada Anda cara mempelajari dan menulis perintah.
StudentID | NamaSiswa | NamaOrangtua | Nomor Telepon | Alamat | Kota | Negara |
1 | Vihaan | Akriti Mehra | 9955339966 | Brigade Jalan Blok 9 | Hyderabad | India |
2 | Manasa | Shourya Sharma | 9234568762 | Jalan Mayo 15 | Kolkata | India |
3 | Anay | Soumya Mishra | 9876914261 | Rumah Marathalli No 101 | Bengaluru | India |
4 | Preeti | Rohan Sinha | 9765432234 | Ratu Jalan 40 | Delhi | India |
5 | Shanaya | Abhinay Agarwal | 9878969068 | Jalan Oberoi 21 | Mumbai | India |
Sebelum kita mulai memahami berbagai perintah yang digunakan di SQL Server, mari kita pahami apa itu SQL Server, arsitekturnya, dan cara menginstalnya.
Apa itu SQL Server?
Microsoft SQL Server adalah sistem manajemen basis data relasional. Ini mendukung bahasa Kueri Terstruktur dan dilengkapi dengan implementasi bahasa SQL-nya sendiri yang merupakan Transact-SQL(T-SQL) . Ini memiliki lingkungan terintegrasi untuk menangani database SQL, yaitu SQL Server Management Studio.
Komponen utama SQL Server adalah sebagai berikut:
- Mesin Database: Komponen ini menangani penyimpanan, Pemrosesan transaksi yang cepat, dan Pengamanan Data.
- SQL Server – Layanan ini digunakan untuk memulai, menghentikan, menjeda, dan melanjutkan instance MS SQL Server.
- Agen SQL Server – Layanan Agen Server memainkan peran penjadwal tugas dan dipicu oleh peristiwa apa pun atau sesuai kebutuhan.
- Browser SQL Server – Layanan ini digunakan untuk menghubungkan permintaan yang masuk ke instance SQL Server yang diinginkan.
- Pencarian Teks Lengkap SQL Server – Digunakan untuk memungkinkan pengguna menjalankan kueri teks lengkap terhadap data karakter dalam tabel SQL.
- Penulis VSS SQL Server – Memungkinkan pencadangan dan pemulihan file data saat SQL Server tidak berjalan.
- Layanan Analisis Server SQL (SSAS) – Layanan ini digunakan untuk menyediakan kemampuan analisis data, penambangan data, dan pembelajaran mesin. SQL Server juga terintegrasi dengan Python dan R untuk analisis data tingkat lanjut.
- Layanan Pelaporan SQL Server (SSRS) – Seperti namanya, layanan ini digunakan untuk menyediakan fitur dan kemampuan pengambilan keputusan termasuk integrasi dengan Hadoop.
- Layanan Integrasi SQL Server (SSIS) – Layanan ini digunakan untuk melakukan operasi ETL untuk berbagai jenis data dari berbagai sumber data.
Sekarang, setelah Anda mengetahui apa itu MS SQL Server, mari kita lanjutkan artikel ini tentang tutorial SQL Server dan memahami cara menginstal dan menyiapkan SQL Server.
Instal SQL Server
Ikuti langkah-langkah di bawah ini untuk menginstal SQL Server:
Langkah 1: Buka halaman resmi unduhan Microsoft SQL Server , di mana Anda akan menemukan opsi untuk menginstal SQL Server baik di tempat atau di awan.
Langkah 2: Sekarang, gulir ke bawah dan Anda akan melihat dua opsi: Edisi Pengembang &Perusahaan . Di sini, saya akan mengunduh edisi Pengembang . Untuk mengunduh, Anda hanya perlu mengeklik Unduh sekarang pilihan. Lihat di bawah.
Langkah 3: Setelah aplikasi diunduh, klik dua kali pada file dan Anda akan melihat jendela berikut.
Langkah 4: Sekarang, Anda dapat memilih salah satu dari 3 opsi untuk mengatur SQL Server. Di sini, saya hanya akan memilih opsi Dasar . Saat memilih opsi jenis instalasi, layar berikutnya adalah menerima perjanjian lisensi. Untuk melakukannya, klik Terima di jendela berikut.
Langkah 5: Selanjutnya, Anda harus menentukan lokasi instalasi SQL Server. Kemudian, Anda harus mengklik Instal.
Setelah Anda mengeklik Pasang , Anda akan melihat bahwa paket yang diperlukan sedang diunduh. Sekarang, setelah instalasi selesai, Anda akan melihat layar berikut:
Di sini, Anda dapat melanjutkan dan mengeklik Hubungkan Sekarang, atau Anda dapat Menyesuaikan instalasi. Untuk pemahaman Anda yang lebih baik, saya akan melanjutkan dan memilih Sesuaikan.
Langkah 6: Setelah Anda mengeklik Sesuaikan di jendela di atas, Anda akan melihat wizard berikut terbuka. di jendela berikut, klik Berikutnya.
Langkah 7 Setelah aturan dipasang secara otomatis, klik Berikutnya . Lihat di bawah.
Langkah 8: Selanjutnya, Anda harus memilih jenis instalasi. Jadi, pilih Lakukan penginstalan baru SQL Server 2017 pilihan dan kemudian klik Berikutnya.
Langkah 9: Di wizard yang terbuka, pilih edisi:Developer. Kemudian, klik Berikutnya . Lihat di bawah.
Langkah 10: Sekarang, baca dan terima perjanjian lisensi dengan check-in tombol radio lalu klik Berikutnya . Lihat di bawah.
Langkah 11 Dalam wizard di bawah ini Anda dapat memilih fitur yang ingin Anda instal. Juga, Anda dapat memilih direktori root instance dan kemudian klik Berikutnya . Di sini, saya akan memilih Layanan Mesin Basis Data .
Langkah 12: Selanjutnya Anda harus memberi nama instance, dan secara otomatis ID instance akan dibuat. Di sini, saya akan memberi nama instance "edureka". Kemudian, klik Berikutnya.
Langkah 13: Di wizard Konfigurasi Server, klik Berikutnya .
Langkah 14: Sekarang, Anda harus mengaktifkan mode otentikasi. Di sini, Anda akan melihat mode otentikasi Windows dan Mode Campuran . Saya akan memilih Mode Campuran. Kemudian, sebutkan kata sandinya dan saya akan menambahkan pengguna saat ini sebagai Admin dengan memilih Tambahkan Pengguna Saat Ini pilihan.
Langkah 15: Kemudian, pilih jalur file konfigurasi dan klik Instal .
Setelah instalasi selesai, Anda akan melihat layar berikut:
Hubungkan ke SQL Server menggunakan SSMS
Setelah SQL Server diinstal, langkah Anda selanjutnya adalah menghubungkan SQL Server ke SQL Server Management Studio. Untuk melakukannya ikuti langkah-langkah di bawah ini:
Langkah 1: Kembali, ke jendela berikut, dan klik instal SSMS pilihan.
Langkah 2: Setelah Anda mengklik opsi itu, Anda akan diarahkan ke halaman berikut, di mana Anda harus memilih Unduh SSMS.
Langkah 3: Setelah pengaturan diunduh, klik dua kali pada aplikasi dan Anda akan melihat wizard berikut terbuka.
Langkah 4: Klik Opsi penginstalan , di jendela di atas dan Anda akan melihat bahwa penginstalan akan dimulai.
Langkah 5: Setelah instalasi selesai Anda akan mendapatkan kotak dialog seperti yang ditunjukkan di bawah ini.
Setelah Anda menginstal SSMS, langkah selanjutnya adalah mengakses Database Engine .
Mengakses Mesin Basis Data
Saat Anda membuka studio manajemen server SQL dari menu mulai , sebuah jendela akan terbuka mirip dengan jendela yang ditunjukkan pada gambar di bawah ini.
Di sini, sebutkan Nama Server, Mode Otentikasi dan klik Hubungkan.
Setelah Anda mengeklik Hubungkan , Anda akan melihat layar berikut.
Baiklah teman-teman, begitulah cara Anda menginstal dan menyiapkan SQL Server. Sekarang, melangkah maju dalam tutorial SQL Server ini, mari kita pahami berbagai komponen arsitektur SQL Server.
Arsitektur SQL Server
Arsitektur SQL Server adalah sebagai berikut:
- Server Di sinilah layanan SQL diinstal dan database berada
- Mesin Relasional Berisi pengurai kueri, pengoptimal, dan pelaksana; dan eksekusi terjadi di mesin relasional.
- Pengurai Perintah Memeriksa sintaks kueri dan mengonversi kueri ke bahasa mesin.
- Pengoptimal Mempersiapkan rencana eksekusi sebagai output dengan mengambil statistik, kueri, dan pohon Aljabar sebagai input.
- Pelaksana Kueri Ini adalah tempat di mana kueri dijalankan selangkah demi selangkah
- Mesin Penyimpanan Ini bertanggung jawab untuk penyimpanan dan pengambilan data pada sistem penyimpanan, manipulasi data, pengelolaan dan penguncian transaksi.
Sekarang, setelah Anda mengetahui cara menyiapkan dan menginstal SQL Server dan berbagai komponennya, mari kita mulai menulis perintah di SQL Server. Tapi, sebelum itu izinkan saya membahas cara menulis komentar di SQL Server.
Komentar di SQL Server
Ada dua cara Anda dapat berkomentar dalam SQL, yaitu menggunakan s komentar satu baris atau m komentar akhir baris .
Komentar Satu Baris
Komentar satu baris dimulai dengan dua tanda hubung (–). Oleh karena itu, teks yang disebutkan setelah (–), hingga akhir satu baris akan diabaikan oleh kompilator.
Contoh:
--Example of single line comments
Komentar Multi-Baris
Komentar multi-baris dimulai dengan /* dan diakhiri dengan */ . Oleh karena itu, teks yang disebutkan di antara /* dan */ akan diabaikan oleh compiler.
Contoh:
/* Example for multi-line comments */
Sekarang di artikel tentang tutorial SQL Server ini, mari kita mulai dengan kumpulan perintah pertama yaitu perintah Bahasa Definisi Data.
Perintah Bahasa Definisi Data
Bagian artikel ini akan memberi Anda gambaran tentang perintah-perintah yang dapat digunakan untuk menentukan basis data Anda. Perintahnya adalah sebagai berikut:
- BUAT
- TURUN
- UBAH
- POTONGKAH
- GANTI NAMA
BUAT
Pernyataan ini digunakan untuk membuat tabel, database, atau tampilan.
Pernyataan 'CREATE DATABASE'
Pernyataan ini digunakan untuk membuat database.
Sintaks
CREATE DATABASE DatabaseName;
Contoh
CREATE DATABASE Students;
Pernyataan 'CREATE TABLE'
Seperti namanya, pernyataan ini digunakan untuk membuat tabel.
Sintaks
CREATE TABLE TableName ( Column1 datatype, Column2 datatype, Column3 datatype, .... ColumnN datatype );
Contoh
CREATE TABLE StudentInfo ( StudentID int, StudentName varchar(8000), ParentName varchar(8000), PhoneNumber int, AddressofStudent varchar(8000), City varchar(8000), Country varchar(8000) );
LEPASKAN
Pernyataan ini digunakan untuk menghapus tabel, database, atau tampilan yang sudah ada.
Pernyataan 'DROP DATABASE'
Pernyataan ini digunakan untuk menghapus database yang sudah ada. Informasi lengkap yang ada dalam database akan hilang segera setelah Anda menjalankan perintah di bawah ini.
Sintaks
DROP DATABASE DatabaseName;
Contoh
DROP DATABASE Students;
Pernyataan 'DROP TABLE'
Pernyataan ini digunakan untuk menghapus tabel yang sudah ada. Informasi lengkap yang ada di tabel akan hilang segera setelah Anda menjalankan perintah di bawah ini.
Sintaks
DROP TABLE TableName;
Contoh
DROP TABLE StudentInfo;
UBAH
Perintah ALTER digunakan untuk menambah, menghapus, atau mengubah kolom atau batasan dalam tabel yang ada.
Pernyataan 'ALTER TABLE'
Pernyataan ini digunakan untuk menambah, menghapus, mengubah kolom dalam tabel yang sudah ada sebelumnya.
Pernyataan 'ALTER TABLE' dengan ADD/DROP COLUMN
Pernyataan ALTER TABLE digunakan dengan perintah ADD/DROP Column untuk menambah dan menghapus kolom.
Sintaks
ALTER TABLE TableName ADD ColumnName Datatype; ALTER TABLE TableName DROP COLUMN ColumnName;
Contoh
--ADD Column BloodGroup: ALTER TABLE StudentInfo ADD BloodGroup varchar(8000); --DROP Column BloodGroup: ALTER TABLE StudentInfo DROP COLUMN BloodGroup ;
Pernyataan 'ALTER TABLE' dengan ALTER COLUMN
Pernyataan ALTER TABLE dapat digunakan dengan kolom ALTER untuk mengubah tipe data kolom yang ada dalam tabel.
Sintaks
ALTER TABLE TableName ALTER COLUMN ColumnName Datatype;
Contoh
--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;
POTONGKAT
Perintah SQL ini digunakan untuk menghapus informasi yang ada dalam tabel tetapi tidak menghapus tabel itu sendiri. Jadi, jika Anda ingin menghapus informasi yang ada di tabel, dan tidak menghapus tabel itu sendiri, Anda harus menggunakan perintah TRUNCATE. Jika tidak, gunakan perintah DROP.
Sintaks
TRUNCATE TABLE TableName;
Contoh
TRUNCATE TABLE StudentInfo;
GANTI NAMA
Pernyataan ini digunakan untuk mengganti nama satu atau beberapa tabel.
Sintaks
sp_rename 'OldTableName', 'NewTableName';
Contoh
sp_rename 'StudentInfo', 'Infostudents';
Berlanjut di artikel tutorial SQL Server ini, mari kita pahami berbagai tipe data yang didukung oleh SQL Server.
Tipe Data SQL Server
Kategori Jenis Data | Nama Tipe Data | Deskripsi | Rentang/ Sintaks |
Angka persis | numerik | Digunakan untuk menyimpan nilai numerik dan memiliki presisi tetap dan nomor skala | – 10^38 +1 hingga 10^38 – 1. |
tinyint | Digunakan untuk menyimpan nilai integer | 0 hingga 255 | |
kecil | Digunakan untuk menyimpan nilai integer | -2^15 (-32,768) hingga 2^15-1 (32,767) | |
besar | Digunakan untuk menyimpan nilai integer | -2^63 (-9.223.372.036.854.775.808) hingga 2^63-1 (9.223.372.036.854.775.807) | |
int | Digunakan untuk menyimpan nilai integer | -2^31 (-2.147.483.648) hingga 2^31-1 (2.147.483.647) | |
bit | Menyimpan tipe data integer yang memiliki nilai 0, 1 atau NULL | 0, 1, atau NULL | |
desimal | Digunakan untuk menyimpan nilai numerik dan memiliki presisi tetap dan nomor skala | – 10^38 +1 hingga 10^38 – 1. | |
uang kecil | Digunakan untuk menyimpan nilai moneter atau mata uang. | – 214.748.3648 hingga 214.748.3647 | |
uang | Digunakan untuk menyimpan nilai moneter atau mata uang. | -922,337,203,685,477,5808 hingga 922,337,203,685,477,5807 (-922,337,203,685,477,58 ke 922.337.203.685.477,58 untuk Informatica. | |
Perkiraan angka | float | Digunakan untuk menyimpan data numerik titik-mengambang | – 1.79E+308 hingga -2.23E-308, 0 dan 2.23E-308 hingga 1.79E+308 |
nyata | Digunakan untuk menyimpan data numerik titik-mengambang | – 3.40E + 38 hingga -1.18E – 38, 0 dan 1.18E – 38 hingga 3.40E + 38 | |
Tanggal dan waktu | tanggal | Digunakan untuk menentukan tanggal di SQL Server. | Sintaks:tanggal |
waktu kecil | Digunakan untuk menentukan tanggal yang digabungkan dengan waktu; di mana waktu didasarkan pada 24 jam sehari, dengan detik selalu nol (:00) dan tanpa pecahan detik. | Sintaks:smalldatetime | |
datetime | Digunakan untuk menentukan tanggal yang digabungkan dengan waktu dalam sehari dengan pecahan detik berdasarkan jam 24 jam. | Sintaks:datetime | |
datetime2 | datetime2 adalah sebagai perpanjangan dari datetime . yang ada jenis yang memiliki presisi pecahan default yang lebih besar, rentang tanggal terbesar. | Sintaks:datetime2 | |
datetimeoffset | Digunakan untuk menentukan tanggal yang digabungkan dengan waktu dalam sehari yang memiliki kesadaran zona waktu. Ini didasarkan pada jam 24 jam. | Sintaks:datetimeoffset | |
waktu | Digunakan untuk menentukan waktu dalam sehari. | Sintaks:waktu | |
String karakter | char | Digunakan untuk menyimpan karakter berukuran tetap. | char [ ( n ) ] dimana nilai n bervariasi dari 1 – 8,000 |
varchar | Digunakan untuk menyimpan karakter dengan panjang variabel. | varchar [ ( n | max ) ] di mana nilai n bervariasi dari 1-8000 dan penyimpanan maksimum yang diizinkan adalah 2GB. | |
teks | Digunakan untuk menyimpan data non-Unicode dengan panjang variabel | Panjang string maksimum yang diizinkan – 2^31-1 (2.147.483.647) | |
String karakter Unicode | nchar | Digunakan untuk menyimpan karakter berukuran tetap. | nchar [ ( n ) ] di mana nilai n bervariasi dari 1-4000 |
nvarchar | Digunakan untuk menyimpan karakter dengan panjang variabel. | varchar [ ( n | max ) ] di mana nilai n bervariasi dari 1-4000 dan penyimpanan maksimum yang diizinkan adalah 2GB. | |
ntext | Digunakan untuk menyimpan data Unicode dengan panjang variabel | Panjang string maksimum yang diizinkan – 2^30-1 (2.147.483.647) | |
String biner | biner | Digunakan untuk menyimpan tipe data biner dengan panjang tetap | biner [ ( n ) ] dimana nilai n bervariasi dari 1 – 8,000 |
varbinary | Digunakan untuk menyimpan tipe data biner dengan panjang tetap | varbinary [ ( n ) ] di mana n vale bervariasi dari 1-8000 dan penyimpanan maksimum yang diizinkan adalah 2^31-1 byte. | |
gambar | Digunakan untuk menyimpan data biner dengan panjang variabel | 0 – 2^31-1 (2.147.483.647) byte | |
Jenis data lainnya | kursor | Ini adalah tipe data untuk prosedur tersimpan atau variabel parameter OUTPUT yang berisi referensi ke kursor. | – |
rowversion | Digunakan untuk mengekspos bilangan biner unik yang dibuat secara otomatis dalam database. | – | |
hierarchyid | Digunakan untuk mewakili posisi dalam hierarki. | – | |
pengidentifikasi unik | Adalah GUID 16-byte. | Sintaks:pengenal unik | |
sql_variant | Digunakan untuk menyimpan nilai dari berbagai tipe data yang didukung SQL Server | Sintaks:sql_variant | |
xml | Digunakan untuk menyimpan tipe data XML. | xml ( [ KONTEN | DOKUMEN ] xml_schemacollection ) | |
Jenis Geometri Spasial | Digunakan untuk merepresentasikan data dalam sistem koordinat Euclidean (datar). | – | |
Jenis Geografi Spasial | Digunakan untuk menyimpan data ellipsoidal (bulat-bumi), seperti koordinat lintang dan bujur GPS. | – | |
tabel | Digunakan untuk menyimpan kumpulan hasil untuk diproses di lain waktu | – |
Selanjutnya, dalam artikel ini mari kita pahami berbagai jenis kunci dan batasan dalam database.
Berbagai Jenis Kunci Dalam Basis Data
Berikut ini adalah berbagai jenis kunci yang digunakan dalam database:
- Kunci Kandidat – Candidate Key adalah sekumpulan atribut yang dapat mengidentifikasi tabel secara unik. Sebuah tabel dapat memiliki lebih dari satu kunci kandidat, dan dari kunci kandidat yang dipilih, satu kunci dipilih sebagai Kunci Utama.
- Kunci Super – Himpunan atribut dapat secara unik mengidentifikasi sebuah tuple. Jadi, kunci kandidat, kunci unik, dan kunci utama adalah kunci super, tetapi sebaliknya.
- Kunci Utama – Kunci utama digunakan untuk mengidentifikasi setiap tupel secara unik.
- Kunci Alternatif – Kunci Alternatif adalah kunci kandidat yang tidak dipilih sebagai Kunci Utama.
- Kunci Unik – Kunci unik mirip dengan kunci utama, tetapi memungkinkan satu nilai NULL di kolom.
- Kunci Asing – Atribut yang hanya dapat mengambil nilai yang ada sebagai nilai dari beberapa atribut lain, adalah kunci asing untuk atribut yang dirujuk.
- Kunci Gabungan – Kunci komposit adalah kombinasi dari dua atau lebih kolom yang mengidentifikasi setiap tupel secara unik.
Kendala yang Digunakan Dalam Basis Data
Konstrain digunakan dalam database untuk menentukan aturan untuk data yang disimpan dalam tabel. Berbagai jenis batasan dalam SQL adalah sebagai berikut:
- BUKAN NULL
- UNIK
- PERIKSA
- DEFAULT
- INDEX
BUKAN NULL
Konstrain NOT NULL memastikan bahwa kolom tidak boleh memiliki nilai NULL.
Contoh
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;
UNIK
Batasan ini memastikan bahwa semua nilai dalam kolom adalah unik.
Contoh
--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
- PERBARUI
- HAPUS
- MERGE
- PILIH
- CUBE
- ROLLUP
- OFFSET
- FETCH
- TOP
- PIVOT
Selain dari perintah ini, ada juga operator/fungsi manipulatif lainnya seperti:
- Operators
- Operator Aritmatika
- Assignment Operators
- Bitwise Operators
- Operator Perbandingan
- Compound Operators
- Operator Logika
- Scope Resolution Operators
- Set Operators
- String Concatenation Operators
- Fungsi Agregat
- 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');
PERBARUI
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. Lihat di bawah.
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:
- BERBEDA
- PESAN OLEH
- GROUP MENURUT
- GROUPING SETS
- KALUSUS MEMILIKI
- 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 kata kunci.
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
Pernyataan ini digunakan dengan fungsi agregat untuk mengelompokkan kumpulan hasil menurut satu atau beberapa kolom.
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:
- Operator Aritmatika
- Assignment Operators
- Bitwise Operators
- Operator Perbandingan
- Compound Operators
- Operator Logika
- 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
Terutama ada tiga set operasi:UNION, INTERSECT, MINUS. Anda dapat merujuk ke gambar di bawah ini untuk memahami operasi yang ditetapkan dalam 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. Mereka adalah:
- 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;
NOTE: 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 yang dilengkapi dengan pelatihan langsung yang dipimpin instruktur dan pengalaman proyek kehidupan nyata. This training will help you understand MySQL in-depth and help you achieve mastery over the subject. Ada pertanyaan untuk kami? Please mention it in the comments section of ”SQL Server Tutorial ” dan saya akan menghubungi Anda kembali.