Dbms SQL Server1
Dbms SQL Server1
Dbms SQL Server1
Insert into table_name values(col1,col2,col3) ..If you are adding values for
all the columns in the table, then there is no need to specify the column
name in the sql query.
[Unit 1: Introduction to Web Design] Course: NIELIT ‘O’ Level (IT)
Module: M2-R5: Web Designing & Publishing
5 Update Statement
Update statement is used to modify the existing records in a table.
Update syntax:
Update <table_name> set col_name = value where <condition>
alter table employee add constraint df_basic default 20000 for basicpay
[Unit 1: Introduction to Web Design] Course: NIELIT ‘O’ Level (IT)
Module: M2-R5: Web Designing & Publishing
13 commands
SELECT ROW_NUMBER() OVER (ORDER BY EMP_code1) AS
ID ,emp_name from employee
columns.
The columns must have similar data types
Union operator selects only distinct values , to allow duplicate values select
union all
[Unit 1: Introduction to Web Design] Course: NIELIT ‘O’ Level (IT)
Module: M2-R5: Web Designing & Publishing
15 Except
The SQL server Except function compares the result set of two queries and
returns the distinct rows from the first query that are not output by the second
query. In other words, the except subtracts the result set of a query from
another.
Query1
Except
Query2
[Unit 1: Introduction to Web Design] Course: NIELIT ‘O’ Level (IT)
Module: M2-R5: Web Designing & Publishing
16 Truncate
The TRUNCATE TABLE statement in SQL Server is a DDL (Data Definition
Language) command. This statement is used to removes all rows from the
table or specified partition without removing the table structure. It is
similar to the DELETE command, but it does not allow filtering the table
records because we cannot use the WHERE clause with this command.
However, in terms of time and resource usage, TRUNCATE is much faster
than DELETE.
This command deallocates the data pages while removing the data in the
table. It is similar to dropping and re-creating the table again.
[Unit 1: Introduction to Web Design] Course: NIELIT ‘O’ Level (IT)
Module: M2-R5: Web Designing & Publishing
17 Offset and fetch
The FETCH and OFFSET clauses in SQL Server are used in combination with the
SELECT and ORDER BY clauses to limit the range of records returned by the query.
It was first introduced with the SQL Server version 2012 for doing pagination of
the result set. It is useful when our database contains a huge amount of data.
OFFSET: This clause is used to specify the beginning point for returning rows from
a result set. Basically, it ignores the initial set of records. SQL Server can use it only
with the ORDER BY clause. If its value is negative, an error will be returned.
Therefore, it should always be greater than or equal to zero.
FETCH: It is an optional clause that provides the number of rows we want to return
after the OFFSET in a query. We cannot use it without OFFSET. Its value cannot be
negative similar to OFFSET. Therefore, it should always be greater than or equal to
zero; otherwise, it will throw an error.
[Unit 1: Introduction to Web Design] Course: NIELIT ‘O’ Level (IT)
Module: M2-R5: Web Designing & Publishing
18 Offset and fetch
SELECT * FROM <tablename>
ORDER BY <colname>
OFFSET 5 ROWS
FETCH NEXT 4 ROWS ONLY;
[Unit 1: Introduction to Web Design] Course: NIELIT ‘O’ Level (IT)
Module: M2-R5: Web Designing & Publishing
19 Join
The inner join returns all records from multiple tables that satisfy the specified join condition. It
is the simple and most popular form of the join. If we omit the inner keyword of the join, we
receive the same output.
SELECT columns FROM table1
INNER JOIN table2 ON condition1 INNER JOIN table3 ON condition2
OUTER JOIN in SQL Server returns all records from both tables that
satisfy the join condition. In other words, this join will not return only the
matching record but also return all unmatched rows from one or both tables.
We can categories the OUTER JOIN further into three types:
LEFT OUTER JOIN
END
[Unit 1: Introduction to Web Design] Course: NIELIT ‘O’ Level (IT)
Module: M2-R5: Web Designing & Publishing
32 Stored Procedures
Modifying the stored procedure
Use the ALTER PROCEDURE statement to modify the existing stored procedure.
ALTER PROCEDURE [dbo].[studentcount]
@cnt as numeric(5) output
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
--SET NOCOUNT on;
Global variable.
Every local variable scope has the restriction to the current batch or
@@CONNECTIONS
@@MAX_CONNECTIONS
@@CPU_BUSY
@@ERROR
@@IDLE
@@LANGUAGE
@@TRANCOUNT
@@VERSION
[Unit 1: Introduction to Web Design] Course: NIELIT ‘O’ Level (IT)
Module: M2-R5: Web Designing & Publishing
36 Global Variable
@@SERVERNAME :
This is used to find the name of the machine/computer on which SQL Server
is running
@@CONNECTIONS :
This is used to find number of logins or attempted logins since SQL Server
was last started.
@@MAX_CONNECTIONS :
This is used to find the maximum number of simultaneous connections that
can be made with SQL Server or instance in this computer environment.
[Unit 1: Introduction to Web Design] Course: NIELIT ‘O’ Level (IT)
Module: M2-R5: Web Designing & Publishing
37 Global Variable
@@CPU_BUSY :
This is used to find the amount of time, in microseconds, that the CPU has
spent doing SQL Server work since the last time SQL Server was running.
@@ERROR :
This is used to check the error status (succeeded or failed) of the most
recently executed statement. It contains Zero (0) if the previous transaction
succeeded, else, it contains the last error number generated by the system.
@@IDLE :
The amount of time, in microseconds, that SQL Server has been idle since it
was last started.
[Unit 1: Introduction to Web Design] Course: NIELIT ‘O’ Level (IT)
Module: M2-R5: Web Designing & Publishing
38 Global Variable
@@LANGUAGE :
This is used to find the name of the language that is currently used by the
SQL Server.
@@TRANCOUNT :
This is used to count the number of open transactions in the current session.
@@VERSION :
This is used to find the current version of the SQL Server Software.
[Unit 1: Introduction to Web Design] Course: NIELIT ‘O’ Level (IT)
Module: M2-R5: Web Designing & Publishing
39 Variables
Before using any variable in batch or procedure, you need to declare the variable.
DECLARE command is used to DECLARE variable which acts as a placeholder for
the memory location.
Only once the declaration is made, a variable can be used in the subsequent part of
batch or procedure.
Rules:
Initialization is an optional thing while declaring.
To declare more than one local variable, use a comma after the first local variable
definition, and then define the next local variable name and data type.
[Unit 1: Introduction to Web Design] Course: NIELIT ‘O’ Level (IT)
Module: M2-R5: Web Designing & Publishing
40 Variables
Assigning a value to SQL Variable
You can assign a value to a variable in the following three ways:
Using SET
Using SELECT
[Unit 1: Introduction to Web Design] Course: NIELIT ‘O’ Level (IT)
Module: M2-R5: Web Designing & Publishing
41 Conditional Statement
Conditional statements in the SQL server help you to define different logics and
actions for different conditions. It allows you to perform different actions based on
conditions defined within the statement.
IF… Else statement in SQL Server
In MS SQL, IF…ELSE is a type of Conditional statement.
If <condition>
Statement/Block of statements
Else
Statements Block of statement
[Unit 1: Introduction to Web Design] Course: NIELIT ‘O’ Level (IT)
Module: M2-R5: Web Designing & Publishing
42 Rules
BEGIN
SELECT
CASE
END AS Location
END
[Unit 1: Introduction to Web Design] Course: NIELIT ‘O’ Level (IT)
Module: M2-R5: Web Designing & Publishing
44 SQL Cursor
SQL cursor is one of the most popular database objects. It is used to retrieve
data from the result set of an SQL query one row at a time. Even if the cursor
is not recommended from a performance perspective, they are still widely
used especially when handling a small amount of data.
1 DECLARE <Cursor_name> CURSOR FOR <Source_SQL_Query>
[Unit 1: Introduction to Web Design] Course: NIELIT ‘O’ Level (IT)
Module: M2-R5: Web Designing & Publishing
45 cursor
DECLARE @var1 NVARCHAR(50)
DECLARE @var2 NVARCHAR(50)
WHILE @@FETCH_STATUS = 0
BEGIN
FETCH NEXT FROM csr INTO @col1, @col2
END
CLOSE csr
Deallocate csr
[Unit 1: Introduction to Web Design] Course: NIELIT ‘O’ Level (IT)
Module: M2-R5: Web Designing & Publishing
46 functions
String functions
Upper
Lower
Left
Right
Reverse
Concat
Replicate
Substring(expression,start,length)
Ltrim
RTrim
Len
[Unit 1: Introduction to Web Design] Course: NIELIT ‘O’ Level (IT)
Module: M2-R5: Web Designing & Publishing
47 String function
Stuff function
The STUFF() function deletes a part of a string and then inserts another
Day
Month
Year
Datepart – year,month,week,day
value.
ISNULL ( Expression, Replacement )
[Unit 1: Introduction to Web Design] Course: NIELIT ‘O’ Level (IT)
Module: M2-R5: Web Designing & Publishing
50 Row_number
WITH dup_cte AS (
SELECT
studID,
rollNo,
Name,
ROW_NUMBER() OVER(
PARTITION BY
studID,
rollNo,
Name
ORDER BY
studID,
rollNo,
Name
) row_num
FROM students
) select * from dup_cte
[Unit 1: Introduction to Web Design] Course: NIELIT ‘O’ Level (IT)
Module: M2-R5: Web Designing & Publishing
51
WITH dup_cte AS (
SELECT
studID,
rollNo,
Name,
COUNT(*) occurrences
FROM students
GROUP BY
studID,
rollNo,
Name
HAVING COUNT(*) > 1
)
SELECT students.studID, students.rollNo, students.Name FROM students INNER JOIN dup_cte ON dup_cte.studID= students.studID
AND
dup_cte.rollNo = students.rollNo
AND
dup_cte.Name = students.Name
ORDER BY
students.studID,
students.rollNo,
students.Name;
[Unit 1: Introduction to Web Design] Course: NIELIT ‘O’ Level (IT)
Module: M2-R5: Web Designing & Publishing
52
WITH dup_cte AS (
SELECT
studID,
rollNo,
Name,
ROW_NUMBER() OVER(
PARTITION BY
studID,
rollNo,
Name
ORDER BY
studID,
rollNo,
Name
) row_num
FROM students
) delete from dup_cte where row_num > 1
select * from students
[Unit 1: Introduction to Web Design] Course: NIELIT ‘O’ Level (IT)
Module: M2-R5: Web Designing & Publishing
53 Rank
SELECT first_name, last_name, city,
RANK () OVER (ORDER BY city) AS Rank_No
FROM rankdemo;
DENSE_RANK() Function
This function assigns a unique rank for each row within a partition as per the
User-Defined Functions
Functions that are defined by the system are known as system functions. In
other words, all the built-in functions supported by the server are referred to
as System functions. The built-in functions save us time while performing the
specific task. These types of functions usually work with the SQL SELECT
statement to calculate values and manipulate data.
[Unit 1: Introduction to Web Design] Course: NIELIT ‘O’ Level (IT)
Module: M2-R5: Web Designing & Publishing
59 System functions
String Functions (LEN, SUBSTRING, REPLACE, CONCAT, TRIM)
Date and Time Functions (datetime, datetime2, smalldatetime)
Aggregate Functions (COUNT, MAX, MIN, SUM, AVG)
Mathematical Functions (ABS, POWER, PI, EXP, LOG)
Ranking Functions (RANK, DENSE_RANK, ROW_NUMBER)
[Unit 1: Introduction to Web Design] Course: NIELIT ‘O’ Level (IT)
Module: M2-R5: Web Designing & Publishing
60 Functions
Functions that are created by the user in the system database or a user-
defined database are known as user-defined functions. The UDF functions
accept parameters, perform actions, and returns the result. These functions
help us to simplify our development by encapsulating complex business logic
and making it available for reuse anywhere based on the needs. The user-
defined functions make the code needed to query data a lot easier to write.
They also improve query readability and functionality, as well as allow other
users to replicate the same procedures.
SQL Server categorizes the user-defined functions mainly into two types:
Scalar Functions
Table-Valued Functions
[Unit 1: Introduction to Web Design] Course: NIELIT ‘O’ Level (IT)
Module: M2-R5: Web Designing & Publishing
61 functions
Scalar function in SQL Server always accepts parameters, either single or multiple
and returns a single value. The scalar functions are useful in the simplification of
our code. Suppose we might have a complex computation that appears in a number
of queries. In such a case, we can build a scalar function that encapsulates the
formula and uses it in each query instead of in each query.
CREATE FUNCTION schema_name.function_name (parameter_list)
RETURNS data_type AS
BEGIN
statements
RETURN value
END
[Unit 1: Introduction to Web Design] Course: NIELIT ‘O’ Level (IT)
Module: M2-R5: Web Designing & Publishing
62 Table valued function
Table-valued functions in SQL Server are the user-defined function that returns
data of a table type. Since this function's return type is a table, we can use it the
same way as we use a table.
Inline Table-Values Functions
This UDF function returns a table variable based on the action performed by the