SlideShare a Scribd company logo
1 of 22
Enhancements in
DML and XML DML
4
New Features of SQL Server 2008 / Session 4 2
Introduction

Some enhancements to Transact-SQL in DML
statements are:

Table value constructors

Table-valued parameters

MERGE statement

Enhanced GROUP BY clause, ROLLUP, and
CUBE operations

Enhanced XML SQL data type and XML
schema
New Features of SQL Server 2008 / Session 4 3
Table Value Constructor 1-4
VALUES ( <row value expression list> ) [ ,...n ]
<row value expression list> ::=
{<row value expression> } [ ,...n ]
<row value expression> ::=
{ DEFAULT | NULL | expression }
Syntax
where,
VALUES: row value expression lists enclosed in
parentheses and separated by a comma
DEFAULT: inserts the default value defined for a column
if defined, otherwise, NULL
expression: can be a constant, a variable, or an
expression

Are also called row constructors

Allows to add multiple rows to a table using a
single INSERT statement
New Features of SQL Server 2008 / Session 4 4
Table Value Constructor 2-4
Example
--Inserting multiple rows using table value constructor
INSERT INTO Customer (CustomerId, Name, Grade, Rank) VALUES
(1 , 'Timothy Brown','A', 1),
(2 , 'Ambrose Pears' ,'B', 1),
(3 , 'Betty Scott', 'A', 2)
Here, using only a single INSERT statement, three rows have been
inserted. This is because of table value constructors.
Output
New Features of SQL Server 2008 / Session 4 5
Table Value Constructor 3-4

Features:

Table value constructor allows to insert
maximum 1000 rows

To insert more than 1000 rows, use:

multiple INSERT statements

bcp utility

BULK INSERT statement

Can also be used to insert multiple rows
having DEFAULT and NULL columns
New Features of SQL Server 2008 / Session 4 6
Table Value Constructor 3-4
Example
INSERT INTO Customer VALUES
(14, 'Weng Lee', NULL, 12),
(15, 'Rose Sanders', 'B', NULL),
(16, 'Mark Preston', NULL, NULL),
(17, 'Rob Mallory', 'A', 11)
For the first customer, the grade is optional, for the
second, the rank is optional, for the third both are
optional and for the last, both are specified.
Output
New Features of SQL Server 2008 / Session 4 7
Table-Valued Parameters 1-3

Enables multiple rows of data to be sent to a
stored procedure

Need not use several parameters, XML, or
temporary tables to pass multiple rows of data

Very tedious in earlier versions of SQL Server
New Features of SQL Server 2008 / Session 4 8
Table-Valued Parameters 2-3

Is newly introduced in SQL Server 2008

Minimizes the additional server-side processing

Allows to create a variable of type table and pass
it to a stored procedure

Must be declared with READONLY attribute

Are actually temporary tables that are stored on
the server

Support both joins and queries
where,
schema_name: is the schema name
type_name: is the user-defined type name or alias type
<column_definition>: defines the columns for a
user-defined table type
<table_constraint>: can be PRIMARY KEY, UNIQUE, or
CHECK
CREATE TYPE [ schema_name. ] type_name
{
AS TABLE ( { <column_definition> }
[ <table_constraint> ] [ ,...n ] )
} [ ; ]
SyntaxThe following example creates a table type, called
EmployeeType.
Example
--Creating a TABLE type named EmployeeType
CREATE TYPE EmployeeType
AS TABLE
(EmployeeId int, Name varchar(50), Salary int,
DepartmentId int);
New Features of SQL Server 2008 / Session 4 9
Table-Valued Parameters 3-3
--Creating stored procedure with table valued parameter of type
--EmployeeType
CREATE PROCEDURE AddEmployee (@EmployeeList EmployeeType READONLY)
AS
SELECT * FROM @EmployeeList
GO
--Creating variable of type EmployeeType and populating it with
--values
DECLARE @EmployeeTable EmployeeType;
INSERT INTO @EmployeeTable VALUES
(4, 'Ethel George', 75000, 2);
INSERT INTO @EmployeeTable VALUES
(5, 'Robert Bernstein', 50000, 2);
--Passing the variable as an argument to the stored procedure
EXEC AddEmployee @EmployeeTable
OutputA stored procedure, AddEmployee, is created and a
variable, EmployeeList, of type EmployeeType is
passed to it.
EmployeeList is a table-valued parameter.
New Features of SQL Server 2008 / Session 4 10
MERGE Statement 1-3

Allows to maintain a target table based on join
conditions on a source table using a single
statement

Enables to perform following in one MERGE
statement:

Insert a new row from the source if the row is missing
in the target

Update a target row if a record already exists in the
source table

Delete a target row if the row is missing in the source
table
New Features of SQL Server 2008 / Session 4 11
MERGE Statement 2-3
MERGE target_table USING source_table
ON match_condition WHEN MATCHED THEN UPDATE SET Col1 =
val1 [, Col2 = val2...]
WHEN [TARGET] NOT MATCHED THEN INSERT (Col1 [,Col2...]
VALUES (Val1 [,Val2...])
WHEN NOT MATCHED BY SOURCE THEN DELETE [OUTPUT $action,
Inserted.Col1, Deleted.Col1,...] ;
Syntax
where,
target_table: is the table where changes are being made
source_table: is the table from which rows will be inserted, updated,
or deleted into target table
match_conditions: are the JOIN conditions and any other
comparison operators
MATCHED: true if a row in the target_table and source_table matches
the match_condition
NOT MATCHED: true if a row from the source_table does not exist in the
target_table
SOURCE NOT MATCHED: true if a row exists in the target_table but not in
the source_table
OUTPUT: An optional clause that allows to view those records that have
been inserted/deleted/updated in target_table
MERGE statements are terminated with a semi-colon (;)
New Features of SQL Server 2008 / Session 4 12
MERGE Statement 3-3
Example
--Create a MERGE statement with CustomerMaster as
target table and CustomerTemp as source table
MERGE INTO CustomerMaster AS T USING CustomerTemp AS
S ON T.CustomerId = S.CustomerId
WHEN MATCHED THEN UPDATE SET T.Name = S.Name,
T.ContactNumber = S.ContactNumber WHEN NOT MATCHED
THEN INSERT (CustomerId, Name, ContactNumber) VALUES
(S.CustomerId, S.Name, S.ContactNumber)
WHEN NOT MATCHED BY SOURCE THEN DELETE
--Display the results
OUTPUT $action, Inserted.CustomerId, Inserted.Name,
Deleted.CustomerId, Deleted.Name;
In this code, CustomerTemp and CustomerMaster table are the
source and target tables respectively. The match condition is the column,
CustomerId, of both tables. If the match condition evaluates to false
(NOT MATCHED), then new records are inserted in the target table.
If match condition evaluates to true (MATCHED), then records are updated
into the target table from the source table.
If records present in the target table do not match with those of source
table (NOT MATCHED BY SOURCE), then these are deleted from the target
table.
The last statement displays a report consisting of rows that were inserted/
updated/ deleted as shown in the output.
Output
New Features of SQL Server 2008 / Session 4 13
“GROUPING SETS” 1-2

Supports aggregation of multiple column
groupings and an optional grand total

More efficient to use GROUPING SETS
operators than multiple GROUP BY with
UNION clauses
where,
grouping set list: consists of one or more
columns, separated by commas
A pair of parentheses, (), without any column name
denotes grand total.
GROUP BY
GROUPING SETS ( <grouping set list> )
Syntax
New Features of SQL Server 2008 / Session 4 14
“GROUPING SETS” 2-2
The example uses GROUPING SETS to display average marks
for every student. NULL values in Name indicate average marks
for every student. NULL value in both Id and Name columns
indicate grand total.
Example
SELECT Id, Name, AVG(Marks) Marks FROM Students
GROUP BY GROUPING SETS
(
(Id, Name, Marks),
(Id),
()
)
Output
New Features of SQL Server 2008 / Session 4 15
"ROLLUP()", "CUBE()", and "GROUPING_ID()” 1-6

ROLLUP()

Is used with GROUP BY clause and can generate
aggregate rows, super-aggregate rows, or
cumulative rows, and a grand total row

Returns n + 1 groupings including a grand total
row, where n denotes number of grouping
elements

Changing of column order changes the output of
ROLLUP()
SELECT a, b, c, function ( <expression> )
FROM <object>
GROUP BY ROLLUP (a,b,c)
Syntax
where,
a, b, c: are elements in composite column list
function: is an SQL function, such as avg(), sum()
<expression>: is an SQL expression

GROUPING_ID() function – newly
introduced

Existing ROLLUP() and CUBE()
operators - enhanced
New Features of SQL Server 2008 / Session 4 16
"ROLLUP()", "CUBE()", and "GROUPING_ID()” 2-6
Example
SELECT DepartmentId, EmployeeId, Avg(Salary) AS
Average_Salary FROM Employee
GROUP BY ROLLUP (DepartmentId, EmployeeId);
Output
New Features of SQL Server 2008 / Session 4 17
"ROLLUP()", "CUBE()", and "GROUPING_ID()” 3-6

CUBE()

Is used with GROUP BY clause

Can generate a grouping of all permutations of
elements in the <composite element list>
present in GROUP BY clause

Number of groupings after performing CUBE
operation equals 2n, where n is the number of
elements in the <composite element list>

Column order does not change the output of
CUBE()
SELECT a, b, c, function ( <expression> )
FROM <object>
GROUP BY ROLLUP (a,b,c)
Syntax
It generates one row for each unique combination of values of
(a, b, c), (a, b), (a, c), (b, c), (a), (b), and (c).
It also calculates a subtotal for each row and a grand total row.
New Features of SQL Server 2008 / Session 4 18
"ROLLUP()", "CUBE()", and "GROUPING_ID()” 4-6
Example
Output
SELECT EmployeeId, DepartmentId, Avg(Salary) AS
Average_Salary FROM Employee GROUP BY CUBE
(EmployeeId, DepartmentId);
New Features of SQL Server 2008 / Session 4 19
"ROLLUP()", "CUBE()", and "GROUPING_ID()” 5-6

GROUPING ID()

Is a function used to find out the grouping set
responsible for producing a particular result row

One can provide all those elements as input to
the function that were used in a grouping set
after a ROLLUP or CUBE operation

Returns a unique integer for each grouping set
that can be used to filter out all unrelated rows
and display only relevant rows
GROUPING_ID()
GROUPING_ID ( <column_expression> [ ,...n ] )
Syntax
where,
<column_expression>: A column expression used in
a GROUP BY clause
New Features of SQL Server 2008 / Session 4 20
"ROLLUP()", "CUBE()", and "GROUPING_ID()” 6-6
Example
SELECT GROUPING_ID(EmployeeId, DepartmentId) AS
GROUP_ID, EmployeeId,
DepartmentId, Avg(Salary) as Average_Salary
FROM Employee
GROUP BY CUBE (EmployeeId, DepartmentId)
HAVING GROUPING_ID(EmployeeId, DepartmentId) > 0;
Output
New Features of SQL Server 2008 / Session 4 21
GROUPING SETS Algebra 1-2
The example contains a combination of two
GROUPING SETS in the GROUP BY clause.
Example
SELECT Id, Name, AVG(Marks) AverageMarks FROM Students
GROUP BY
GROUPING SETS
(
(Id, Marks),
()
),
GROUPING SETS
(
(Name)
);
Output
 A query can have multiple GROUPING
SETS with a GROUP BY clause
 Separate GROUPING SETS clauses by
commas
 A comma represents a Cartesian product
between two GROUPING SETS clauses
New Features of SQL Server 2008 / Session 4 22
GROUPING SETS Algebra 2-2
Example
SELECT Id, Name, AVG(Marks) AverageMarks FROM Students
GROUP BY
GROUPING SETS
(
(Id, Marks, Name),
(Name)
);
The query in the example is equivalent to the Cartesian product of
two GROUPING SETS clauses.
Name is combined with each of the other groups:
Output

More Related Content

What's hot (20)

SQL
SQLSQL
SQL
 
Sql wksht-3
Sql wksht-3Sql wksht-3
Sql wksht-3
 
DDL,DML,SQL Functions and Joins
DDL,DML,SQL Functions and JoinsDDL,DML,SQL Functions and Joins
DDL,DML,SQL Functions and Joins
 
Sql DML
Sql DMLSql DML
Sql DML
 
Sql ch 5
Sql ch 5Sql ch 5
Sql ch 5
 
Sql dml & tcl 2
Sql   dml & tcl 2Sql   dml & tcl 2
Sql dml & tcl 2
 
1. dml select statement reterive data
1. dml select statement reterive data1. dml select statement reterive data
1. dml select statement reterive data
 
Sql commands
Sql commandsSql commands
Sql commands
 
Sql wksht-6
Sql wksht-6Sql wksht-6
Sql wksht-6
 
Les01 (retrieving data using the sql select statement)
Les01 (retrieving data using the sql select statement)Les01 (retrieving data using the sql select statement)
Les01 (retrieving data using the sql select statement)
 
Oracle SQL DML Statements
Oracle SQL DML StatementsOracle SQL DML Statements
Oracle SQL DML Statements
 
Sql
SqlSql
Sql
 
Merging data (1)
Merging data (1)Merging data (1)
Merging data (1)
 
The Database Environment Chapter 8
The Database Environment Chapter 8The Database Environment Chapter 8
The Database Environment Chapter 8
 
SQL select statement and functions
SQL select statement and functionsSQL select statement and functions
SQL select statement and functions
 
SQL Fundamentals
SQL FundamentalsSQL Fundamentals
SQL Fundamentals
 
Module 3
Module 3Module 3
Module 3
 
Chap 7
Chap 7Chap 7
Chap 7
 
Ch04
Ch04Ch04
Ch04
 
Ch05
Ch05Ch05
Ch05
 

Viewers also liked

Physical Tharapist
Physical Tharapist Physical Tharapist
Physical Tharapist ABUENO52
 
111214 hospital la-fe-spain-mind_byte_presentation
111214 hospital la-fe-spain-mind_byte_presentation111214 hospital la-fe-spain-mind_byte_presentation
111214 hospital la-fe-spain-mind_byte_presentationSerafin Arroyo
 
Cancer drug could help fight parkinson's
Cancer drug could help fight parkinson'sCancer drug could help fight parkinson's
Cancer drug could help fight parkinson'sOther Mother
 
Printcatalog229594
Printcatalog229594Printcatalog229594
Printcatalog229594ozwashroom
 
School of social work faith based community collaborative visual
School of social work faith based community collaborative visualSchool of social work faith based community collaborative visual
School of social work faith based community collaborative visualjuanbtoribio
 

Viewers also liked (10)

Physical Tharapist
Physical Tharapist Physical Tharapist
Physical Tharapist
 
111214 hospital la-fe-spain-mind_byte_presentation
111214 hospital la-fe-spain-mind_byte_presentation111214 hospital la-fe-spain-mind_byte_presentation
111214 hospital la-fe-spain-mind_byte_presentation
 
Cancer drug could help fight parkinson's
Cancer drug could help fight parkinson'sCancer drug could help fight parkinson's
Cancer drug could help fight parkinson's
 
Schizophrenia
SchizophreniaSchizophrenia
Schizophrenia
 
Lynching in america
Lynching in americaLynching in america
Lynching in america
 
PALEA
PALEAPALEA
PALEA
 
Printcatalog229594
Printcatalog229594Printcatalog229594
Printcatalog229594
 
School of social work faith based community collaborative visual
School of social work faith based community collaborative visualSchool of social work faith based community collaborative visual
School of social work faith based community collaborative visual
 
Courses
CoursesCourses
Courses
 
Robert koch
Robert kochRobert koch
Robert koch
 

Similar to Sql server ___________session 3(sql 2008)

Similar to Sql server ___________session 3(sql 2008) (20)

DML Commands
DML CommandsDML Commands
DML Commands
 
Sql (DBMS)
Sql (DBMS)Sql (DBMS)
Sql (DBMS)
 
Ch 9 S Q L
Ch 9  S Q LCh 9  S Q L
Ch 9 S Q L
 
Review of SQL
Review of SQLReview of SQL
Review of SQL
 
SQL Query
SQL QuerySQL Query
SQL Query
 
2. DBMS Experiment - Lab 2 Made in SQL Used
2. DBMS Experiment - Lab 2 Made in SQL Used2. DBMS Experiment - Lab 2 Made in SQL Used
2. DBMS Experiment - Lab 2 Made in SQL Used
 
Exploring collections with example
Exploring collections with exampleExploring collections with example
Exploring collections with example
 
Creating database using sql commands
Creating database using sql commandsCreating database using sql commands
Creating database using sql commands
 
chapter 8 SQL.ppt
chapter 8 SQL.pptchapter 8 SQL.ppt
chapter 8 SQL.ppt
 
Query
QueryQuery
Query
 
SQL
SQLSQL
SQL
 
SQL Overview
SQL OverviewSQL Overview
SQL Overview
 
Lab
LabLab
Lab
 
Adbms 21 sql 99 schema definition constraints and queries
Adbms 21 sql 99 schema definition constraints and queriesAdbms 21 sql 99 schema definition constraints and queries
Adbms 21 sql 99 schema definition constraints and queries
 
Unit-1 SQL fundamentals.docx SQL commands used to create table, insert values...
Unit-1 SQL fundamentals.docx SQL commands used to create table, insert values...Unit-1 SQL fundamentals.docx SQL commands used to create table, insert values...
Unit-1 SQL fundamentals.docx SQL commands used to create table, insert values...
 
Database Architecture and Basic Concepts
Database Architecture and Basic ConceptsDatabase Architecture and Basic Concepts
Database Architecture and Basic Concepts
 
Intro to tsql unit 9
Intro to tsql   unit 9Intro to tsql   unit 9
Intro to tsql unit 9
 
Oraclesql
OraclesqlOraclesql
Oraclesql
 
Sql commands
Sql commandsSql commands
Sql commands
 
chap 7.ppt(sql).ppt
chap 7.ppt(sql).pptchap 7.ppt(sql).ppt
chap 7.ppt(sql).ppt
 

More from Ehtisham Ali

Sql server ___________session_20(ddl triggers)
Sql server  ___________session_20(ddl triggers)Sql server  ___________session_20(ddl triggers)
Sql server ___________session_20(ddl triggers)Ehtisham Ali
 
Sql server ___________session3-normailzation
Sql server  ___________session3-normailzationSql server  ___________session3-normailzation
Sql server ___________session3-normailzationEhtisham Ali
 
Sql server ___________session2-data_modeling
Sql server  ___________session2-data_modelingSql server  ___________session2-data_modeling
Sql server ___________session2-data_modelingEhtisham Ali
 
Sql server ___________session_19(triggers)
Sql server  ___________session_19(triggers)Sql server  ___________session_19(triggers)
Sql server ___________session_19(triggers)Ehtisham Ali
 
Sql server ___________session_18(stored procedures)
Sql server  ___________session_18(stored procedures)Sql server  ___________session_18(stored procedures)
Sql server ___________session_18(stored procedures)Ehtisham Ali
 
Sql server ___________session_17(indexes)
Sql server  ___________session_17(indexes)Sql server  ___________session_17(indexes)
Sql server ___________session_17(indexes)Ehtisham Ali
 
Sql server ___________session_16(views)
Sql server  ___________session_16(views)Sql server  ___________session_16(views)
Sql server ___________session_16(views)Ehtisham Ali
 
Sql server ___________session_15(data integrity)
Sql server  ___________session_15(data integrity)Sql server  ___________session_15(data integrity)
Sql server ___________session_15(data integrity)Ehtisham Ali
 
Sql server ___________session_11-12(joins)
Sql server  ___________session_11-12(joins)Sql server  ___________session_11-12(joins)
Sql server ___________session_11-12(joins)Ehtisham Ali
 
Sql server ___________session_10(group by clause)
Sql server  ___________session_10(group by clause)Sql server  ___________session_10(group by clause)
Sql server ___________session_10(group by clause)Ehtisham Ali
 
Sql server ___________session_1-intro
Sql server  ___________session_1-introSql server  ___________session_1-intro
Sql server ___________session_1-introEhtisham Ali
 
Sql server ___________session 2(sql 2008)
Sql server  ___________session 2(sql 2008)Sql server  ___________session 2(sql 2008)
Sql server ___________session 2(sql 2008)Ehtisham Ali
 
Sql server ___________session 1(sql 2008)
Sql server  ___________session 1(sql 2008)Sql server  ___________session 1(sql 2008)
Sql server ___________session 1(sql 2008)Ehtisham Ali
 
Sql server ___________data type of sql server
Sql server  ___________data type of sql serverSql server  ___________data type of sql server
Sql server ___________data type of sql serverEhtisham Ali
 
Sql server ___________data control language
Sql server  ___________data control languageSql server  ___________data control language
Sql server ___________data control languageEhtisham Ali
 
Sql server ___________ (advance sql)
Sql server  ___________  (advance sql)Sql server  ___________  (advance sql)
Sql server ___________ (advance sql)Ehtisham Ali
 

More from Ehtisham Ali (17)

Android tutorial
Android tutorialAndroid tutorial
Android tutorial
 
Sql server ___________session_20(ddl triggers)
Sql server  ___________session_20(ddl triggers)Sql server  ___________session_20(ddl triggers)
Sql server ___________session_20(ddl triggers)
 
Sql server ___________session3-normailzation
Sql server  ___________session3-normailzationSql server  ___________session3-normailzation
Sql server ___________session3-normailzation
 
Sql server ___________session2-data_modeling
Sql server  ___________session2-data_modelingSql server  ___________session2-data_modeling
Sql server ___________session2-data_modeling
 
Sql server ___________session_19(triggers)
Sql server  ___________session_19(triggers)Sql server  ___________session_19(triggers)
Sql server ___________session_19(triggers)
 
Sql server ___________session_18(stored procedures)
Sql server  ___________session_18(stored procedures)Sql server  ___________session_18(stored procedures)
Sql server ___________session_18(stored procedures)
 
Sql server ___________session_17(indexes)
Sql server  ___________session_17(indexes)Sql server  ___________session_17(indexes)
Sql server ___________session_17(indexes)
 
Sql server ___________session_16(views)
Sql server  ___________session_16(views)Sql server  ___________session_16(views)
Sql server ___________session_16(views)
 
Sql server ___________session_15(data integrity)
Sql server  ___________session_15(data integrity)Sql server  ___________session_15(data integrity)
Sql server ___________session_15(data integrity)
 
Sql server ___________session_11-12(joins)
Sql server  ___________session_11-12(joins)Sql server  ___________session_11-12(joins)
Sql server ___________session_11-12(joins)
 
Sql server ___________session_10(group by clause)
Sql server  ___________session_10(group by clause)Sql server  ___________session_10(group by clause)
Sql server ___________session_10(group by clause)
 
Sql server ___________session_1-intro
Sql server  ___________session_1-introSql server  ___________session_1-intro
Sql server ___________session_1-intro
 
Sql server ___________session 2(sql 2008)
Sql server  ___________session 2(sql 2008)Sql server  ___________session 2(sql 2008)
Sql server ___________session 2(sql 2008)
 
Sql server ___________session 1(sql 2008)
Sql server  ___________session 1(sql 2008)Sql server  ___________session 1(sql 2008)
Sql server ___________session 1(sql 2008)
 
Sql server ___________data type of sql server
Sql server  ___________data type of sql serverSql server  ___________data type of sql server
Sql server ___________data type of sql server
 
Sql server ___________data control language
Sql server  ___________data control languageSql server  ___________data control language
Sql server ___________data control language
 
Sql server ___________ (advance sql)
Sql server  ___________  (advance sql)Sql server  ___________  (advance sql)
Sql server ___________ (advance sql)
 

Recently uploaded

Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfUmakantAnnand
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 

Recently uploaded (20)

Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.Compdf
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 

Sql server ___________session 3(sql 2008)

  • 2. New Features of SQL Server 2008 / Session 4 2 Introduction  Some enhancements to Transact-SQL in DML statements are:  Table value constructors  Table-valued parameters  MERGE statement  Enhanced GROUP BY clause, ROLLUP, and CUBE operations  Enhanced XML SQL data type and XML schema
  • 3. New Features of SQL Server 2008 / Session 4 3 Table Value Constructor 1-4 VALUES ( <row value expression list> ) [ ,...n ] <row value expression list> ::= {<row value expression> } [ ,...n ] <row value expression> ::= { DEFAULT | NULL | expression } Syntax where, VALUES: row value expression lists enclosed in parentheses and separated by a comma DEFAULT: inserts the default value defined for a column if defined, otherwise, NULL expression: can be a constant, a variable, or an expression  Are also called row constructors  Allows to add multiple rows to a table using a single INSERT statement
  • 4. New Features of SQL Server 2008 / Session 4 4 Table Value Constructor 2-4 Example --Inserting multiple rows using table value constructor INSERT INTO Customer (CustomerId, Name, Grade, Rank) VALUES (1 , 'Timothy Brown','A', 1), (2 , 'Ambrose Pears' ,'B', 1), (3 , 'Betty Scott', 'A', 2) Here, using only a single INSERT statement, three rows have been inserted. This is because of table value constructors. Output
  • 5. New Features of SQL Server 2008 / Session 4 5 Table Value Constructor 3-4  Features:  Table value constructor allows to insert maximum 1000 rows  To insert more than 1000 rows, use:  multiple INSERT statements  bcp utility  BULK INSERT statement  Can also be used to insert multiple rows having DEFAULT and NULL columns
  • 6. New Features of SQL Server 2008 / Session 4 6 Table Value Constructor 3-4 Example INSERT INTO Customer VALUES (14, 'Weng Lee', NULL, 12), (15, 'Rose Sanders', 'B', NULL), (16, 'Mark Preston', NULL, NULL), (17, 'Rob Mallory', 'A', 11) For the first customer, the grade is optional, for the second, the rank is optional, for the third both are optional and for the last, both are specified. Output
  • 7. New Features of SQL Server 2008 / Session 4 7 Table-Valued Parameters 1-3  Enables multiple rows of data to be sent to a stored procedure  Need not use several parameters, XML, or temporary tables to pass multiple rows of data  Very tedious in earlier versions of SQL Server
  • 8. New Features of SQL Server 2008 / Session 4 8 Table-Valued Parameters 2-3  Is newly introduced in SQL Server 2008  Minimizes the additional server-side processing  Allows to create a variable of type table and pass it to a stored procedure  Must be declared with READONLY attribute  Are actually temporary tables that are stored on the server  Support both joins and queries where, schema_name: is the schema name type_name: is the user-defined type name or alias type <column_definition>: defines the columns for a user-defined table type <table_constraint>: can be PRIMARY KEY, UNIQUE, or CHECK CREATE TYPE [ schema_name. ] type_name { AS TABLE ( { <column_definition> } [ <table_constraint> ] [ ,...n ] ) } [ ; ] SyntaxThe following example creates a table type, called EmployeeType. Example --Creating a TABLE type named EmployeeType CREATE TYPE EmployeeType AS TABLE (EmployeeId int, Name varchar(50), Salary int, DepartmentId int);
  • 9. New Features of SQL Server 2008 / Session 4 9 Table-Valued Parameters 3-3 --Creating stored procedure with table valued parameter of type --EmployeeType CREATE PROCEDURE AddEmployee (@EmployeeList EmployeeType READONLY) AS SELECT * FROM @EmployeeList GO --Creating variable of type EmployeeType and populating it with --values DECLARE @EmployeeTable EmployeeType; INSERT INTO @EmployeeTable VALUES (4, 'Ethel George', 75000, 2); INSERT INTO @EmployeeTable VALUES (5, 'Robert Bernstein', 50000, 2); --Passing the variable as an argument to the stored procedure EXEC AddEmployee @EmployeeTable OutputA stored procedure, AddEmployee, is created and a variable, EmployeeList, of type EmployeeType is passed to it. EmployeeList is a table-valued parameter.
  • 10. New Features of SQL Server 2008 / Session 4 10 MERGE Statement 1-3  Allows to maintain a target table based on join conditions on a source table using a single statement  Enables to perform following in one MERGE statement:  Insert a new row from the source if the row is missing in the target  Update a target row if a record already exists in the source table  Delete a target row if the row is missing in the source table
  • 11. New Features of SQL Server 2008 / Session 4 11 MERGE Statement 2-3 MERGE target_table USING source_table ON match_condition WHEN MATCHED THEN UPDATE SET Col1 = val1 [, Col2 = val2...] WHEN [TARGET] NOT MATCHED THEN INSERT (Col1 [,Col2...] VALUES (Val1 [,Val2...]) WHEN NOT MATCHED BY SOURCE THEN DELETE [OUTPUT $action, Inserted.Col1, Deleted.Col1,...] ; Syntax where, target_table: is the table where changes are being made source_table: is the table from which rows will be inserted, updated, or deleted into target table match_conditions: are the JOIN conditions and any other comparison operators MATCHED: true if a row in the target_table and source_table matches the match_condition NOT MATCHED: true if a row from the source_table does not exist in the target_table SOURCE NOT MATCHED: true if a row exists in the target_table but not in the source_table OUTPUT: An optional clause that allows to view those records that have been inserted/deleted/updated in target_table MERGE statements are terminated with a semi-colon (;)
  • 12. New Features of SQL Server 2008 / Session 4 12 MERGE Statement 3-3 Example --Create a MERGE statement with CustomerMaster as target table and CustomerTemp as source table MERGE INTO CustomerMaster AS T USING CustomerTemp AS S ON T.CustomerId = S.CustomerId WHEN MATCHED THEN UPDATE SET T.Name = S.Name, T.ContactNumber = S.ContactNumber WHEN NOT MATCHED THEN INSERT (CustomerId, Name, ContactNumber) VALUES (S.CustomerId, S.Name, S.ContactNumber) WHEN NOT MATCHED BY SOURCE THEN DELETE --Display the results OUTPUT $action, Inserted.CustomerId, Inserted.Name, Deleted.CustomerId, Deleted.Name; In this code, CustomerTemp and CustomerMaster table are the source and target tables respectively. The match condition is the column, CustomerId, of both tables. If the match condition evaluates to false (NOT MATCHED), then new records are inserted in the target table. If match condition evaluates to true (MATCHED), then records are updated into the target table from the source table. If records present in the target table do not match with those of source table (NOT MATCHED BY SOURCE), then these are deleted from the target table. The last statement displays a report consisting of rows that were inserted/ updated/ deleted as shown in the output. Output
  • 13. New Features of SQL Server 2008 / Session 4 13 “GROUPING SETS” 1-2  Supports aggregation of multiple column groupings and an optional grand total  More efficient to use GROUPING SETS operators than multiple GROUP BY with UNION clauses where, grouping set list: consists of one or more columns, separated by commas A pair of parentheses, (), without any column name denotes grand total. GROUP BY GROUPING SETS ( <grouping set list> ) Syntax
  • 14. New Features of SQL Server 2008 / Session 4 14 “GROUPING SETS” 2-2 The example uses GROUPING SETS to display average marks for every student. NULL values in Name indicate average marks for every student. NULL value in both Id and Name columns indicate grand total. Example SELECT Id, Name, AVG(Marks) Marks FROM Students GROUP BY GROUPING SETS ( (Id, Name, Marks), (Id), () ) Output
  • 15. New Features of SQL Server 2008 / Session 4 15 "ROLLUP()", "CUBE()", and "GROUPING_ID()” 1-6  ROLLUP()  Is used with GROUP BY clause and can generate aggregate rows, super-aggregate rows, or cumulative rows, and a grand total row  Returns n + 1 groupings including a grand total row, where n denotes number of grouping elements  Changing of column order changes the output of ROLLUP() SELECT a, b, c, function ( <expression> ) FROM <object> GROUP BY ROLLUP (a,b,c) Syntax where, a, b, c: are elements in composite column list function: is an SQL function, such as avg(), sum() <expression>: is an SQL expression  GROUPING_ID() function – newly introduced  Existing ROLLUP() and CUBE() operators - enhanced
  • 16. New Features of SQL Server 2008 / Session 4 16 "ROLLUP()", "CUBE()", and "GROUPING_ID()” 2-6 Example SELECT DepartmentId, EmployeeId, Avg(Salary) AS Average_Salary FROM Employee GROUP BY ROLLUP (DepartmentId, EmployeeId); Output
  • 17. New Features of SQL Server 2008 / Session 4 17 "ROLLUP()", "CUBE()", and "GROUPING_ID()” 3-6  CUBE()  Is used with GROUP BY clause  Can generate a grouping of all permutations of elements in the <composite element list> present in GROUP BY clause  Number of groupings after performing CUBE operation equals 2n, where n is the number of elements in the <composite element list>  Column order does not change the output of CUBE() SELECT a, b, c, function ( <expression> ) FROM <object> GROUP BY ROLLUP (a,b,c) Syntax It generates one row for each unique combination of values of (a, b, c), (a, b), (a, c), (b, c), (a), (b), and (c). It also calculates a subtotal for each row and a grand total row.
  • 18. New Features of SQL Server 2008 / Session 4 18 "ROLLUP()", "CUBE()", and "GROUPING_ID()” 4-6 Example Output SELECT EmployeeId, DepartmentId, Avg(Salary) AS Average_Salary FROM Employee GROUP BY CUBE (EmployeeId, DepartmentId);
  • 19. New Features of SQL Server 2008 / Session 4 19 "ROLLUP()", "CUBE()", and "GROUPING_ID()” 5-6  GROUPING ID()  Is a function used to find out the grouping set responsible for producing a particular result row  One can provide all those elements as input to the function that were used in a grouping set after a ROLLUP or CUBE operation  Returns a unique integer for each grouping set that can be used to filter out all unrelated rows and display only relevant rows GROUPING_ID() GROUPING_ID ( <column_expression> [ ,...n ] ) Syntax where, <column_expression>: A column expression used in a GROUP BY clause
  • 20. New Features of SQL Server 2008 / Session 4 20 "ROLLUP()", "CUBE()", and "GROUPING_ID()” 6-6 Example SELECT GROUPING_ID(EmployeeId, DepartmentId) AS GROUP_ID, EmployeeId, DepartmentId, Avg(Salary) as Average_Salary FROM Employee GROUP BY CUBE (EmployeeId, DepartmentId) HAVING GROUPING_ID(EmployeeId, DepartmentId) > 0; Output
  • 21. New Features of SQL Server 2008 / Session 4 21 GROUPING SETS Algebra 1-2 The example contains a combination of two GROUPING SETS in the GROUP BY clause. Example SELECT Id, Name, AVG(Marks) AverageMarks FROM Students GROUP BY GROUPING SETS ( (Id, Marks), () ), GROUPING SETS ( (Name) ); Output  A query can have multiple GROUPING SETS with a GROUP BY clause  Separate GROUPING SETS clauses by commas  A comma represents a Cartesian product between two GROUPING SETS clauses
  • 22. New Features of SQL Server 2008 / Session 4 22 GROUPING SETS Algebra 2-2 Example SELECT Id, Name, AVG(Marks) AverageMarks FROM Students GROUP BY GROUPING SETS ( (Id, Marks, Name), (Name) ); The query in the example is equivalent to the Cartesian product of two GROUPING SETS clauses. Name is combined with each of the other groups: Output