0% found this document useful (0 votes)
6 views

Exam Note SQL

The document provides an overview of various SQL Server functions and expressions, including ISNULL, COALESCE, CASE, UNION, INTERSECT, EXCEPT, and string manipulation functions. It explains the differences between these functions, their syntax, and provides examples of their usage in SQL queries. Additionally, it covers aggregate functions, wildcard usage in LIKE statements, and the CAST and CONVERT functions for data type conversion.

Uploaded by

raj364
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Exam Note SQL

The document provides an overview of various SQL Server functions and expressions, including ISNULL, COALESCE, CASE, UNION, INTERSECT, EXCEPT, and string manipulation functions. It explains the differences between these functions, their syntax, and provides examples of their usage in SQL queries. Additionally, it covers aggregate functions, wildcard usage in LIKE statements, and the CAST and CONVERT functions for data type conversion.

Uploaded by

raj364
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

IS NULL ()

The SQL Server ISNULL () function replaces NULL with a specified value. The following shows the syntax of the ISNULL
() function: ISNULL (expression, replacement)

Input SELECT ISNULL(NULL, 500); Input SELECT ISNULL('Hello', 'W3Schools.com');


Output 500 Output Hello

SELECT CountryCode, CodeType SELECT ISNULL(CountryCode, 0) As CountryCode , ISNULL(CodeType, 'na') As CodeType


FROM LOCATION; FROM LOCATION;

COALESCE ()
The SQL Server COALESCE expression accepts a number of arguments, evaluates them in sequence, and returns the
first non-null argument. The following illustrates the syntax of the COALESCE expression:

Input SELECT COALESCE(NULL, NULL, 100, 200);


Output 100

Input SELECT COALESCE(NULL, 'Hello', 'Hi', NULL);


Output Hello

SELECT first_name, last_name, phone, email


FROM Customers
ORDER BY first_name, last_name

SELECT first_name, last_name, COALESCE(phone,'N/A') phone, email


FROM Customers
ORDER BY first_name, last_name
Difference between COALESCE() and ISNULL()
 ISNULL can handle only two parameters: the expression to check and the replacement value.
COALESCE, on the other hand, can handle multiple expressions and returns the first non-NULL value.
 ISNULL is specific to SQL Server,
while COALESCE is a standard SQL function supported by multiple database systems.
 ISNULL evaluates the replacement value even if the expression is not NULL,
whereas COALESCE evaluates expressions in the order specified and stops once it finds a non-NULL value.

CASE ()
The CASE expression goes through conditions and returns a value when the first condition is met (like an if-then-else
statement). So, once a condition is true, it will stop reading and return the result. If no conditions are true, it returns the
value in the ELSE clause. If there is no ELSE part and no conditions are true, it returns NULL. The CASE expression has
two formats: simple CASE expression and searched CASE expression.

A. Example- Using simple CASE expression in the SELECT clause example

SELECT
CASE order_status
WHEN 1 THEN 'Pending’
WHEN 2 THEN 'Processing’
WHEN 3 THEN 'Rejected’
WHEN 4 THEN 'Completed’
END AS order_status,
COUNT(order_id) order_count
FROM orders
WHERE YEAR (order_date) = 2018
GROUP BY order_status;

B. Example- Using simple CASE expression in AGGREGATE FUNCTION example

SELECT
SUM(CASE WHEN order_status = 1 THEN 1 ELSE 0 END) AS 'Pending’,
SUM(CASE WHEN order_status = 2 THEN 1 ELSE 0 END) AS 'Processing’,
SUM(CASE WHEN order_status = 3 THEN 1 ELSE 0 END) AS 'Rejected’,
SUM(CASE WHEN order_status = 4 THEN 1 ELSE 0 END) AS 'Completed’,
COUNT(*) AS 'Total'
FROM Orders
WHERE YEAR(order_date) = 2018;

C. Example- Using searched CASE expression in SELECT clause example

SELECT o.order_id, SUM(quantity * list_price) order_value,


CASE
WHEN SUM(quantity * list_price) <= 500
THEN 'Very Low'
WHEN SUM(quantity * list_price) > 500 AND
SUM(quantity * list_price) <= 1000
THEN 'Low'
WHEN SUM(quantity * list_price) > 1000 AND
SUM(quantity * list_price) <= 5000
THEN 'Medium'
WHEN SUM(quantity * list_price) > 5000 AND
SUM(quantity * list_price) <= 10000
THEN 'High'
WHEN SUM(quantity * list_price) > 10000
THEN 'Very High’
END order_priority
FROM orders o
INNER JOIN order_items i ON i.order_id = o.order_id
WHERE YEAR(order_date) = 2018
GROUP BY o.order_id

UNION () and UNION ALL ()


UNION removes duplicates while UNION ALL includes them.
SQL Server UNION is one of the set operations that allow you to combine results of two SELECT statements
into a single result set which includes all the rows that belong to the SELECT statements in the union.
The following illustrates the syntax of the SQL Server UNION:

UNION vs JOIN
The join such as INNER JOIN or LEFT JOIN combines
columns from two tables while the UNION
combines rows from two queries. In other words, join
appends the result sets horizontally while union appends
the result set vertically. The following picture illustrates
the main difference between UNION and JOIN:

UNION vs UNION ALL Examples


The following example combines names of staff and customers into a single list:

SELECT
first_name,
last_name
FROM staffs
UNION
SELECT
first_name,
last_name
FROM customers;

SELECT City
FROM Customers
UNION ALL
SELECT City
FROM Suppliers
ORDER BY City;
INTERSECT
The SQL Server INTERSECT combines result sets of two or more queries and returns distinct rows that are
output by both queries.
Similar to the UNION operator, the queries in the
syntax above must conform to the following rules:
 Both queries must have the same number and
order of columns.
 The data type of the corresponding columns
must be the same or compatible.
The following picture illustrates the INTERSECT
operation:
In this illustration, we had two result sets T1 and T2:
 T1 result set includes 1, 2, and 3.
 T2 result set includes 2, 3, and 4.
The intersection of T1 and T2 result sets returns the distinct rows which are 2 and 3.

Example-
SELECT city
FROM customers
INTERSECT
SELECT city
FROM stores
ORDER BY city;

The first query finds all cities of the customers and the second query finds the cities of the stores. The whole
query, which uses INTERSECT, returns the common cities of customers and stores, which are the cities
output by both input queries.

EXCEPT
The EXCEPT operator in SQL is used to retrieve all the
unique records from the left operand (query), except the
records that are present in the result set of the right operand
(query). In other words, this operator compares the distinct
values of the left query with the result set of the right query.
If a value from the left query is found in the result set of the
right query, it is excluded from the final result. For better
understanding consider two tables with records as shown in
the image −

If we perform the EXCEPT operator on the above two tables to retrieve the names, it will display the distinct
records only from the first table which are not in common with the records of the second table.
Here, "Dev" is common in both tables. So, the EXECPT operator will eliminate it and retrieves only "Sara" and
"Jay" as output.

Example-
SELECT product_id
FROM products
EXCEPT
SELECT product_id
FROM order_items
ORDER BY product_id
STRING
MS SQL Server String functions can be applied on string value or will return string value or numeric data.
Following is the list of String functions with examples:

CHAIRINDEX () LEN ()
Search for "t" in string "Customer", and return position: Return the length of a string:

Input SELECT CHARINDEX('t', 'Customer') AS MatchPosition; Input SELECT LEN('W3Schools.com');


Output 4 Output 13

LEFT () RIGHT ()
Extract 3 characters from a string (starting from left): Extract 3 characters from a string (starting from right):

Input SELECT LEFT('SQL Tutorial', 3) AS ExtractString; Input SELECT LEFT('SQL Tutorial', 3) AS ExtractString;
Output SQL Output ial

SUBSTRING ()
Extract 3 characters from a string, starting in position 1:

Input SELECT LEFT('SQL Tutorial', 3) AS ExtractString;


Output SQL

LOWER () UPPER ()
Convert the text to lower-case: Convert the text to upper-case:

Input SELECT LOWER('SQL Tutorial is FUN!'); Input SELECT LOWER('SQL Tutorial is FUN!');
Output sql tutorial is fun! Output SQL TUTORIAL IS FUN!

LTRIM() RTRIM()
Remove leading spaces from a string: Remove leading spaces from a string:

Input SELECT LTRIM(' SQL Tutorial') AS LeftTrimmedString; Input SELECT LTRIM('SQL Tutorial ') AS RightTrimmedString;
Output SQL Tutorial Output SQL Tutorial

REPLACE()
REVERSE()
Replace "T" with "M":
Reverse a string:
Input SELECT REVERSE('SQL Tutorial');
Input SELECT REPLACE('SQL Tutorial', 'T', 'M');
Output lairotuT LQS
Output SQL MuMorial

STUFF()
STR()
Delete 3 characters from a string, starting in position 1, and then
Return a number as a string:
insert "HTML" in position 1:
Input SELECT STR(185);
Input SELECT STUFF('SQL Tutorial', 1, 3, 'HTML');
Output 185
Output HTML Tutorial
PATINDEX()
QUOTENAME() Return the position of a pattern in a string:
Return a Unicode string with bracket delimiters (default): Input SELECT PATINDEX('%schools%', 'W3Schools.com');
Input SELECT QUOTENAME('abcdef'); Output 3
Output [abcdef]
FORMAT()
Format a date:

Input
DECLARE @d DATETIME = '12/01/2018'; CONCAT()
SELECT FORMAT (@d, 'd', 'en-US') AS 'US English Result', Add two strings together:
FORMAT (@d, 'd', 'no') AS 'Norwegian Result', Input SELECT CONCAT('W3Schools', '.com');
FORMAT (@d, 'd', 'zu') AS 'Zulu Result'; Output W3Schools.com

Output
US English Result Norwegian Result Zulu Result
12/1/2018 01.12.2018 12/1/2018

DATE

GETDATE() DATEADD()
Return the current database system date and time: Add one year to a date, then return the date:
Input SELECT GETDATE(); Input SELECT DATEADD(year, 1, '2017/08/25') AS DateAdd;
Output 2024-11-26 23:47:55.177 Output 2018-08-25 00:00:00.000

DATEPART() DATEIF()
Return a specified part of a date: Return the difference between two date values, in years:
Input SELECT DATEPART(year, '2017/08/25') AS DatePartInt; Input SELECT DATEDIFF(year, '2017/08/25', '2011/08/25') AS DateDiff;
Output 2017 Output -6

CONVERT()
It will display the date and time in different formats.
Example: The following queries will return the date and time
in different format in MS SQL Server.
SELECT CONVERT(VARCHAR(19),GETDATE())
SELECT CONVERT(VARCHAR(10),GETDATE(),10)
SELECT CONVERT(VARCHAR(10),GETDATE(),110)

AGGREGATE
An aggregate function performs a calculation one or more values and returns a single value. The aggregate
function is often used with the GROUP BY clause and HAVING clause of the SELECT statement.

AVG()
The following statement use the AVG() function to return the average list price of all products in the products
table:

SELECT AVG(list_price) avg_product_price


FROM products;
SELECT CAST(ROUND(AVG(list_price),2) AS DEC(10,2)) As avg_product_price
FROM products;

First, the ROUND function returns the rounded average list price. And then the CAST function converts the
result to a decimal number with two decimal places.

COUNT()
The following statement uses the COUNT() function to return the number of products whose price is greater
than 500:

SELECT COUNT(*) product_count


FROM products
WHERE list_price > 500

In this example:
 First, the WHERE clause gets products whose list price is greater than 500.
 Second, the COUNT function returns the number of products with list prices greater than 500.

MAX()
The following statement uses the MAX() function to return the highest list price of all products:

SELECT MAX(list_price) max_list_price


FROM products

MIN()
Similarly, the following statement uses the MIN() function to return the lowest list price of all products:
SELECT MIN(list_price) max_list_price
FROM products

SUM()
The following statement uses the SUM() function to calculate the total stock by product id in all warehouses:

SELECT
product_id,
SUM(quantity) stock_count
FROM stocks
GROUP BY product_id
ORDER BY stock_count DESC

Here is how the statement works:


 First, the GROUP BY clause summarized the rows by product id into groups.
 Second, the SUM() function calculated the sum of quantity for each group.
SQL SERVER WILDCARD
The SQL Server LIKE is a logical operator that determines if a character string matches a specified pattern. A pattern
may include regular characters and wildcard characters. The LIKE operator is used in the WHERE clause of the SELECT,
UPDATE, and DELETE statements to filter rows based on pattern matching.

SQL Server LIKE operator


The SQL Server LIKE is a logical operator that determines if a character string matches a specified pattern. A pattern
may include regular characters and wildcard characters. The LIKE operator is used in the WHERE clause of the SELECT,
UPDATE, and DELETE statements to filter rows based on pattern matching.

The % (percent) wildcard- The following example finds the customers whose last name starts with the
letter z:
SELECT customer_id, first_name, last_name
FROM customers
WHERE last_name LIKE 'z%'
ORDER BY first_name

The following example returns the customers whose last name ends with the string er:

SELECT
customer_id,
first_name,
last_name
FROM customers
WHERE last_name LIKE '%er'
ORDER BY first_name

The following statement retrieves the customers whose last name starts with the letter t and ends with
the letter s:

SELECT
customer_id,
first_name,
last_name
FROM customers
WHERE last_name LIKE 't%s'
ORDER BY first_name

The following example returns the customers whose last name ends with the string er:

SELECT
customer_id,
first_name,
last_name
FROM customers
WHERE last_name LIKE '%er'
ORDER BY first_name
The following statement retrieves the customers whose last name starts with the letter t and ends
with the letter s:

SELECT
customer_id,
first_name,
last_name
FROM customers
WHERE last_name LIKE 't%s'
ORDER BY first_name

The _ (underscore) wildcard


The underscore represents a single character. For example, the following statement returns the customers
where the second character is the letter u:

SELECT customer_id, first_name, last_name


FROM customers
WHERE last_name LIKE '_u%'
ORDER BY first_name

The pattern _u%


 The first underscore character (_) matches any single character.
 The second letter u matches the letter u exactly
 The third character % matches any sequence of characters

The [list of characters] wildcard


The square brackets with a list of characters e.g., [ABC] represents a single character that must be one of
the characters specified in the list. For example, the following query returns the customers where the first
character in the last name is Y or Z:

SELECT customer_id, first_name, last_name


FROM customers
WHERE last_name LIKE '[YZ]%'
ORDER BY last_name

The [character-character] wildcard


The square brackets with a character range e.g., [A-C] represent a single character that must be within a
specified range. For example, the following query finds the customers where the first character in the last
name is the letter in the range A through C:

SELECT customer_id, first_name, last_name


FROM customers
WHERE last_name LIKE '[A-C]%'
ORDER BY first_name
The [^Character List or Range] wildcard

The square brackets with a caret sign (^) followed by a range e.g., [^A-C] or character list e.g., [ABC] represent
a single character that is not in the specified range or character list. For example, the following query returns
the customers where the first character in the last name is not the letter in the range A through X:

SELECT customer_id, first_name, last_name


FROM customers
WHERE last_name LIKE '[^A-X]%'
ORDER BY first_name

The NOT LIKE operator


The following example uses the NOT LIKE operator to find customers where the first character in the first
name is not the letter A:

SELECT customer_id, first_name, last_name


FROM customers
WHERE first_name NOT LIKE 'A%'
ORDER BY first_name

CAST () & CONVERT ()


The CAST() function converts a value (of any type) into a specified datatype.

Convert a value to a varchar datatype:


INPUT SELECT CAST(25.65 AS varchar);
OUTPUT 25.65

Convert a value to a datetime datatype:


INPUT SELECT CAST('2017-08-25' AS datetime);
OUTPUT 2017-08-25 00:00:00.000

The following statement uses the CAST() function to convert the monthly sales in 2017 to integer
values.

SELECT
MONTH(order_date) month,
CAST(SUM(quantity * list_price * (1 - discount)) AS INT) amount
FROM orders o
INNER JOIN order_items i ON o.order_id = i.order_id
WHERE YEAR(order_date) = 2017
GROUP BY MONTH(order_date)
ORDER BY month
The CONVERT() function converts a value (of any type) into a specified datatype.

Convert an expression from one data type to another (varchar):


INPUT SELECT CONVERT(varchar, 25.65);
OUTPUT 25.65

Convert an expression from one data type to another (datetime):


INPUT SELECT CONVERT(datetime, '2017-08-25');
OUTPUT 2017-08-25 00:00:00.000

SERVER TEMPORARY DATA STORES


Temporary Table:
Temporary tables provide temporary data storage in exact form of original tables for quick access of data.
Temporary tables are stored in TempDB. They work like a regular table in that you can perform the operations
select, insert and delete as for a regular table. If created inside a stored procedure, they are destroyed upon
completion of the stored procedure.
There are two types of temporary tables; one is local and the other is global.
 Local Temporary Tables
 Global Temporary Tables

Local temporary tables:


Local temporary tables are the tables stored in
tempdb. Local temporary tables are temporary
tables that are available only to the session that
created them. These tables are automatically
destroyed at the termination of the procedure or
session. They are specified with the prefix #, for
example, #table_name, and these temp tables
can be created with the same name in multiple
windows.

Global temporary tables:


Global temporary tables are also stored in
tempdb. Global temporary tables are temporary
tables that are available to all sessions and all
users. They have dropped automatically when
the last session using the temporary table has
been completed. They are specified with the
prefix #, for example, ##table_name.
Subqueries:
A subquery is a query nested inside another statement such as SELECT, INSERT, UPDATE, or DELETE.
Let’s see the following example.

Consider the orders and customers tables from the BikeStores Database. The following statement shows
how to use a subquery in the WHERE clause of a SELECT statement to find the sales orders of the
customers located in New York:

Correlated Subqueries:
A correlated subquery is a subquery that uses the values of the outer query. In other words, the correlated
subquery depends on the outer query for its values. Moreover, a correlated subquery is executed repeatedly,
once for each row evaluated by the outer query. The correlated subquery is also known as a repeating
subquery. Consider the following products table from the BikeStores database.

Types of SQL Server Temporary Data Stores

Table Variables:
Table variables are kinds of variables that allow you to
hold rows of data, which are similar to temporary tables.

Following the TABLE keyword, you define the structure of


the table variable which is similar to the structure of a
regular table that includes column definitions, data type,
size, optional constraint, etc.

For example, the following statement declares a table


variable named @product_table which consists of three
columns: product_name, brand_id, and list_price:
Once declared, the table variable is empty. You can
insert rows into the table variables using the INSERT
statement:

Similar to a temporary table, you can query data from the


table variables using the SELECT statement:

Common Table Expressions (CTE):


CTE stands for common table expression. A CTE allows you to define a temporary named result set that
available temporarily in the execution scope of a statement such as SELECT, INSERT, UPDATE, DELETE, or
MERGE.

(A) Simple SQL Server CTE example


This query uses a CTE to return the sales amounts by sales staffs in 2018:

In this example:
 First, we defined cte_sales_amounts as the name of the common table expression. the CTE returns a
result that that consists of three columns staff, year, and sales derived from the definition query.
 Second, we constructed a query that returns the total sales amount by sales staff and year by querying
data from the orders, order_items and staffs tables.
 Third, we referred to the CTE in the outer query and select only the rows whose year are 2018.

Noted that this example is solely for the demonstration purpose to help you gradually understand how
common table expressions work. There is a more optimal way to achieve the result without using CTE.

B) Using a common table expression to make report averages based on counts


This example uses the CTE to return the average number of sales orders in 2018 for all sales staffs.
VIEWS in SQL Server:
When you use the SELECT statement to query data from one or more tables, you get a result set. For example,
the following statement returns the product name, brand, and list price of all products from the products and
brands tables:

Next time, if you want to get the same result set, you can save this query into a text file, open it, and execute
it again. SQL Server provides a better way to save this query in the database catalog through a view.

A view is a named query stored in the database catalog that allows you to refer to it later.
So, the query above can be stored as a view using the CREATE VIEW statement as follows:

Later, you can reference to the view in the SELECT statement like a table as follows:

Advantages of views:
Generally speaking, views provide the following advantages:

1. Security:
You can restrict users to access directly to a table and allow them to access a subset of data via views.
For example, you can allow users to access customer name, phone, email via a view but restrict them
to access the bank account and other sensitive information.

2. Simplicity:
A relational database may have many tables with complex relationships e.g., one-to-one and one-to-
many that make it difficult to navigate.
However, you can simplify the complex queries with joins and conditions using a set of views.

3. Consistency:
Sometimes, you need to write a complex formula or logic in every query.
To make it consistent, you can hide the complex queries logic and calculations in views.
Once views are defined, you can reference the logic from the views rather than rewriting it in separate
queries.
BETWEEN
The BETWEEN operator is a logical operator that allows you to specify a range to test.
The following illustrates the syntax of the BETWEEN operator:

The following query finds the products whose list prices are between 149.99 and 199.99:

SELECT product_id, product_name, list_price


FROM products
WHERE list_price BETWEEN 149.99 AND 199.99
ORDER BY list_price

To get the products whose list prices are not in the range of 149.99 and 199.99, you use the NOT
BETWEEN operator as follows:

SELECT product_id, product_name, list_price


FROM products
WHERE list_price NOT BETWEEN 149.99 AND 199.99
ORDER BY list_price

The following query finds the orders that customers placed between January 15, 2017 and January 17, 2017:

SELECT order_id, customer_id, order_date, order_status


FROM orders
WHERE order_date BETWEEN '20170115' AND '20170117'
ORDER BY order_date

Notice that to specify a literal date, you use the format ‘YYYYMMDD‘ where YYYY is 4-digits year e.g., 2017,
MM is 2-digits month e.g., 01 and DD is 2-digits day e.g., 15.

ALIASES
When you use the SELECT statement to query data from a table, SQL Server uses the column names as the
column headings for the output. See the following example:
A table can be given an alias which is known as correlation name or range variable.
Similar to the column alias, table alias can be assigned either with or without the AS keyword:

NULLIF
In this session, you will learn how to use the SQL Server NULLIF expression to return NULL if the first
argument equals to the second one. The NULLIF expression accepts two arguments and returns NULL if two
arguments are equal. Otherwise, it returns the first expression.

Using NULLIF expression to translate a blank string to NULL


The NULLIF expression comes in handy when you’re working with legacy data that contains a mixture of null
and empty strings in a column. Consider the following example.

SELECT first_name, last_name, phone


FROM customers
WHERE phone IS NULL
ORDER BY first_name

SELECT first_name, last_name, phone


FROM customers
WHERE NULLIF(phone, '') IS NULL
ORDER BY first_name

IF ELSE
IF STATEMENT
DECLARE @sales INT

SELECT @sales = SUM(list_price * quantity)


FROM order_items i
INNER JOIN sales.orders o ON o.order_id = i.order_id
WHERE YEAR(order_date) = 2018

SELECT @sales
IF @sales > 1000000
BEGIN
PRINT 'Great! The sales amount in 2018 is greater than 1,000,000'
END

Great! The sales amount in 2018 is greater than 1,000,000


IF ELSE STATEMENT

DECLARE @sales INT


SELECT
@sales = SUM(list_price * quantity)
FROM order_items i
INNER JOIN orders o ON o.order_id = i.order_id
WHERE YEAR(order_date) = 2017;

SELECT @sales;
IF @sales > 10000000

BEGIN
PRINT 'Great! The sales amount in 2018 is greater than 10,000,000';
END

ELSE

BEGIN
PRINT 'Sales amount in 2017 did not reach 10,000,000';
END

NESTED IF...ELSE

DECLARE @x INT = 10,


@y INT = 20;

IF (@x > 0)

BEGIN
IF (@x < @y)
PRINT 'x > 0 and x < y';
ELSE
PRINT 'x > 0 and x >= y';
END

WHILE LOOP
SQL WHILE loop provides us with the advantage to execute the SQL statement(s) repeatedly until the
specified condition result turn out to be false. Let’s take an example of using the SQL Server WHILE statement
to understand it better. The following example illustrates how to use the WHILE statement to print out
numbers from 1 to 5:

DECLARE @counter INT = 1;


WHILE @counter <= 5
BEGIN
PRINT @counter;
SET @counter = @counter + 1;
END
SELECT INTO
The SELECT INTO statement creates a new table and inserts rows from the query into it.
The following SELECT INTO statement creates the destination table and copies rows, which satisfy the
WHERE condition, from the source table to the destination table:

If you want to copy the partial data from the source table, you use the WHERE clause to specify which rows
to copy. Similarly, you can specify which columns from the source table to copy to the destination table by
specifying them in the select list.

Using SQL Server SELECT INTO to copy table within the same database example:
The SELECT INTO statement creates a new table and inserts rows from the query into it.
The following SELECT INTO statement creates the destination table and copies rows, which satisfy the
WHERE condition, from the source table to the destination table:

INSERT INTO SELECT


To insert data from other tables into a table, you use the following SQL Server INSERT INTO SELECT
statement:

In this syntax, the statement inserts rows returned by the query into the target_table.

The query is any valid SELECT statement that retrieves data from other tables. It must return the values that
are corresponding to the columns specified in the column_list.

The TOP clause part is optional. It allows you to specify the number of rows returned by the query to be
inserted into the target table. If you use the PERCENT option, the statement will insert the percent of rows
instead. Note that it is a best practice to always use the TOP clause with the ORDER BY clause.
STORED PROCEDURES
SQL Server stored procedures are used to group one or more Transact-SQL statements into logical units. The
stored procedure is stored as a named object in the SQL Server Database Server. When you call a stored
procedure for the first time, SQL Server creates an execution plan and stores it in the cache. In the
subsequent executions of the stored procedure, SQL Server reuses the plan to execute the stored procedure
very fast with reliable performance.

Getting started with SQL Server Stored Procedures


 A basic guide to stored procedures– shows you how to create, execute, modify, and drop a stored
procedure in SQL Server.
 Parameters – learn how to create stored procedures with parameters, including optional parameters.
 Variables – introduce you to Transact-SQL variables and how to manipulate variables in stored
procedures.
 Output Parameters – guide you on how to return data from a stored procedure back to the calling
program using the output parameters.

A basic guide to stored procedures (Creating a simple stored procedure)


The following SELECT statement returns a list of products from the products table in the BikeStores sample
database:
To create a stored procedure that wraps this query, you use the CREATE PROCEDURE statement as follows:

In this syntax:
 The uspProductList is the name of the stored procedure.
 The AS keyword separates the heading and the body of the stored procedure.
 If the stored procedure has one statement, the BEGIN and END keywords surrounding the statement
are optional. However, it is a good practice to include them to make the code clear.

Note that in addition to the CREATE PROCEDURE keywords, you can use the CREATE PROC keywords to
make the statement shorter.

To compile this stored procedure, you execute it as a normal SQL statement in SQL Server Management
Studio as shown in the following picture:
You can find the stored procedure in the Object Explorer, under Programmability > Stored Procedures as
shown in the following picture:

Sometimes, you need to click the Refresh button to manually update the database objects in the Object
Explorer.

Executing a stored procedure


Modifying a stored procedure
To modify an existing stored procedure, you use
the ALTER PROCEDURE statement.

First, open the stored procedure to view its


contents by right-clicking the stored procedure
name and select Modify menu item:

Second, change the body of the stored procedure by sorting the products by list prices instead of product
names:
Deleting a stored procedure

SQL Server Stored Procedure Parameters (Creating a stored procedure with one parameter)

Creating a stored procedure with multiple parameters


Creating text parameters

Creating optional parameters

Using NULL as the default value

Variables
A variable is an object that holds a single value of a specific type e.g., integer, date, or varying character string.
We typically use variables in the following cases:
 As a loop counter to count the number of times a loop is performed.
 To hold a value to be tested by a control-of-flow statement such as WHILE.
 To store the value returned by a stored procedure or a function

Declaring a variable
To declare a variable, you use the DECLARE statement. For example, the following statement declares a
variable named @model_year:
Output Parameters
Advantage of Stored Procedures
1. Better Performance –
The procedure calls are quick and efficient as stored procedures are compiled once and stored in
executable form.Hence the response is quick. The executable code is automatically cached, hence
lowers the memory requirements.

2. Higher Productivity –
Since the same piece of code is used again and again so, it results in higher productivity.

3. Ease of Use –
To create a stored procedure, one can use any Java Integrated Development Environment (IDE). Then,
they can be deployed on any tier of network architecture.

4. Scalability –
Stored procedures increase scalability by isolating application processing on the server.

5. Maintainability –
Maintaining a procedure on a server is much easier than maintaining copies on various client
machines, this is because scripts are in one location.

6. Security –
Access to the Oracle data can be restricted by allowing users to manipulate the data only through
stored procedures that execute with their definer’s privileges.

SAVING, STORAGE & RESTORE MS SQL SERVER DATABASE


Step-1 Right-click on the Database:
In the Object Explorer, right-click on your database (e.g., PharmacyDB).

Step-2 Tasks > Generate Scripts:


Choose "Tasks", then "Generate Scripts".

Step-3 Choose Objects:


Select "Script entire database and all database objects”.

Step-4 Choose Scripting Option:


Select Save to file > files to generate > single file
We can specify the file name and format (e.g., PharmacyDB_Script.sql).
Go Advance> types of data of script> schema & data
Save scripts

You might also like