SQLServer
SQLServer
What is SQL?
SQL (Structured Query Language) is a database computer language designed for
managing data in relational database management systems (RDBMS). SQL, is a
standardized computer language that was originally developed by IBM for querying,
altering and defining relational databases, using declarative statements. There are
various types of statements and each one of them uses certain key words like
SELECT, INSERT etc. These statements are categorized as Data definition
language, data manipulation language etc.
In this chapter, we are going to discuss the following topics:
What is the need of SQL language?
SQL Commands
Operators
Procedures
Triggers
Built-in functions
Scalar functions
Aggregate functions
SQL is an essential part of any database system as it allows to interact with the
database system. A small set of SQL language set is defined as ANSI SQL and it is
designed to standard across all RDBMSs. If you are looking to write a database
independent system, you can use only ANSI SQL (however it severely constrains
the capability of any RDBMS). SQL is important for the following reasons:
Allows users to access data in relational database management systems.
Allows users to define the data in database and manipulate that data.
Allows to embed within other languages using SQL modules, libraries &
pre -compilers.
The Data Definition Language (DDL) manages table and index structure. The most
basic DDL statements includes CREATE, ALTER, RENAME and DROP statements:
CREATE creates an object (a table, for example) in the database.
Create Table
ALTER table is used to modify a table definition. It can perform the following
functions on a table:
It can add a column
Syntax:
Example:
DROP Table
To delete a table using SQL, we use DROP TABLE command:
Syntax:
RENAME a table
To rename a table using code, execute the sp_rename stored procedure using the
following syntax.
RENAME ExistingTableName, TableNewName;
The Data Manipulation Language includes insert, update, delete and select
statements. The Data Manipulation Language (DML) is the subset of SQL used to
add, update and delete data.
'SELECT' Statement - SQL SELECT Statement is used to fetch the data from a
database table which returns data in the form of result table. These result tables are
called result-sets.
Syntax:
The SQL WHERE clause is used to specify a condition while choosing the data from
single table or joining with multiple tables. If the given condition is satisfied, then only
it returns specific value from the table. You would use WHERE clause to filter the
records and fetching only necessary records.
The WHERE clause is not only used in SELECT statement, but it is also used in
UPDATE, DELETE statement.
Syntax:
SELECT ID, NAME, SALARY FROM emp WHERE SALARY > 10000 AND age <
25.
SELECT ID, NAME, SALARY FROM emp WHERE SALARY > 10000 or age < 25.
SQL update statement is used to update selected records from the table. You have
to use WHERE clause with UPDATE query to update selected rows, otherwise all
the rows would be affected.
Syntax:-
Example: -
If you want the data to appear in a particular order you need to use the “order by”
keyword.
Example:
Select * from country order by countryname
Here country is my table name..it will give you result order by countryname.
You can customize this order ascending or descending order.
Select * from country order by countryname desc
Select * from country order by countryname asc
SELECT DISTINCT
Operator Description
= Equal
<> Not equal
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal
BETWEEN Between an inclusive range
LIKE Search for a pattern
IN If you know the exact value you want to return for at least one of
the Columns.
SQL LIKE Clause - The SQL LIKE clause is used to compare a value to
similar values using wildcard operators. There are two wildcards used in
conjunction with the LIKE operator:
Syntax:
IN Operator
The IN operator permits you to specify multiple values in a WHERE clause. The IN
operator is used to compare a value to a list of literal values that have been
specified.
Syntax:
BETWEEN Operators
The BETWEEN operator selects a range of data between two values. The values
can be numbers, text, or dates
Syntax:
TOP Clause
The TOP clause is used to specify the number of records to return. The TOP clause
can be very useful on large tables with thousands of records. Top clause scans the
whole table that’s why Returning a large number of records can impact on
performance.
Syntax:
Example:
You can give a table or a column another name by using an alias. This can be a
good thing to do if you have very long or complex table names or column names.
An alias name can be any user-defined name.
Syntax :
SELECT column_name(s) FROM table_name AS alias_name
5.4 Joins
JOINS are used to use filter the results from the SQL statements SQL server
supports four types of joins. These joins are as follows:
INNER JOIN: Returns all rows when there is at least one match in BOTH
tables. It is the default join of SQL Server
LEFT JOIN: Return all rows from the left table, and the matched rows from
the right table
RIGHT JOIN: Return all rows from the right table, and the matched rows from
the left table
FULL JOIN: Return all rows when there is a match in ONE of the tables
Examples of Joins:
Example :
Output:- 2.
INTERSECT: It retrieves the set of values that are common to both the tables.
It also needs two set of values from two different tables, so that it provides the
similar set of values.
Example:
Output: - 1,3
The HAVING clause was added to SQL because the WHERE keyword could
not be used with aggregate functions.
SQL Constraints
Constraints are the rules enforced on data columns on table. These are used to limit
the type of data that can go into a table. This ensures the accuracy and reliability of
the data in the database. Constraints could be column level or table level. Column
level constraints are applied only to one column, whereas table level constraints are
applied to the whole table.
SQL constraints are used to specify rules for the data in a table.
If there is any violation between the constraint and the data action, the
action is aborted by the constraint.
Constraints can be specified when the table is created (inside the
CREATE TABLE statement) or after the table is created (inside the
ALTER TABLE statement).
Example:
CREATE TABLE PersonsNotNull
(
P_Id int NOT NULL,
LastName varchar (255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)
The UNIQUE and PRIMARY KEY constraints both provide a guarantee for
uniqueness for a column or set of columns. A PRIMARY KEY constraint
automatically has a UNIQUE constraint defined on it. Note that you can have
many UNIQUE constraints per table, but only one PRIMARY KEY constraint per
table.
CREATE TABLE PersonsUnique
(
P_Id int NOT NULL UNIQUE,
LastName varchar (255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)
The PRIMARY KEY constraint uniquely identifies each record in a database table.
Primary keys must contain unique values and cannot contain NULL values. Each
table should have a primary key, and each table can have only ONE primary key.
CREATE TABLE Persons
(
P_Id int NOT NULL PRIMARY KEY,
LastName varchar (255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)
To allow naming of a PRIMARY KEY constraint, and for defining a PRIMARY KEY
constraint on multiple.
Before, we start looking at procedures and functions, lets first look at the variables.
Variables
To use the user-defined variable first you should create the variable. Syntax for
creating the variable is…. DECLARE when you want to define the variables. Local
variables must have the symbol “@” as a prefix. You also need to specify a data
type for your variable (int, varchar(x), etc.).
Example:
declare @val int
set @val=111
If you want to check the value for a variable that you assigned, you can use the
PRINT command like this
print @val
It will return 111.
Example 1: -
Create PROCEDURE [dbo]. [Bindcategory]
as
BEGIN
select CategoryName,CategoryId from categorymaster ;
END
Between this Begin and End block you can write your statements.
Example 2:
Two numbers are passed in and the midpoint of the two numbers is listed:
Cursors
Cursor is a database object used by applications to manipulate data in a set on a
row-by-row basis, it's like recordset in the ASP and visual basic. Let's look at a
cursor first and then we will explain the components and the key words used in it:
OPEN db_cursor
FETCH NEXT FROM db_cursor INTO @name
WHILE @@FETCH_STATUS = 0
BEGIN
SET @fileName = @path + @name + '_' + @fileDate + '.BAK'
BACKUP DATABASE @name TO DISK = @fileName
CLOSE db_cursor
DEALLOCATE db_cursor
Based on the example above, cursors include these components:
DECLARE CURSOR statement - Populate the cursor with values that will
be evaluated
FETCH NEXT statements - Assign the specific values from the cursor to
the variables
NOTE - This logic is used for the initial population before the
WHILE statement and then again during each loop in the process
as a portion of the WHILE statement
CLOSE statement - Releases the current data and associated locks, but
permits the cursor to be re-opened
Types Of Triggers
There are three action query types that you use in SQL which are INSERT,
UPDATE and DELETE. So, there are three types of triggers and hybrids that come
from mixing and matching the events and timings that fire them.
Example : This trigger is fired after an update on the table. Let’s create the
trigger as:-
CREATE TRIGGER trgAfterUpdate ON [dbo].[Employee_Test]
FOR UPDATE
AS
declare @empid int;
declare @empname varchar(100);
declare @empsal decimal(10,2);
declare @audit_action varchar(100);
select @empid=i.Emp_ID from inserted i;
select @empname=i.Emp_Name from inserted i;
select @empsal=i.Emp_Sal from inserted i;
if update(Emp_Name)
set @audit_action='Updated Record -- After Update Trigger.';
if update(Emp_Sal)
set @audit_action='Updated Record -- After Update Trigger.';
insert into
Employee_Test_Audit(Emp_ID,Emp_Name,Emp_Sal,Audit_Action,Audit_Time
stamp)
values(@empid,@empname,@empsal,@audit_action,getdate());
SQL has many built-in functions for performing calculations on data. We have 2
categories of functions, namely aggregate functions and scalar functions. Aggregate
functions return a single value, calculated from values in a column, while scalar
functions return a single value, based on the input value.
Aggregate functions
examples:
AVG () - Returns the average value
STDEV () - Returns the standard deviation value
COUNT () - Returns the number of rows
MAX () - Returns the largest value
MIN () - Returns the smallest value
SUM () - Returns the sum
Scalar functions
Examples:
UPPER () - Converts a field to upper case
LOWER () - Converts a field to lower case
LEN () - Returns the length of a text field
ROUND () - Rounds a numeric field to the number of decimals specified
GETDATE () - Returns the current system date and time
How to use Comments
Using comments in you SQL script is important to make the script easier to read and
understand.
In SQL, there are two types of comments available.
--Single-line comment
/* */ Multiple-line comment
you can comment one line at the time using “--” before the text you want to comment
out.
Syntax:
-- text_of_comment
Example:
--this procedure is for user insert by admin
You can comment several lines using “/*” in the start of the comment and “*/” in the
end of
the comment.
Syntax:
/*
text_of_comment
text_of_comment
*/
Assignments
.
SELECT CustomerName, City FROM Customers;