SlideShare a Scribd company logo
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
Ad

More Related Content

What's hot (20)

SQL
SQLSQL
SQL
zekeLabs Technologies
 
Sql wksht-3
Sql wksht-3Sql wksht-3
Sql wksht-3
Mukesh Tekwani
 
DDL,DML,SQL Functions and Joins
DDL,DML,SQL Functions and JoinsDDL,DML,SQL Functions and Joins
DDL,DML,SQL Functions and Joins
Ashwin Dinoriya
 
Sql DML
Sql DMLSql DML
Sql DML
Vikas Gupta
 
Sql ch 5
Sql ch 5Sql ch 5
Sql ch 5
Mukesh Tekwani
 
Sql dml & tcl 2
Sql   dml & tcl 2Sql   dml & tcl 2
Sql dml & tcl 2
Dr. C.V. Suresh Babu
 
1. dml select statement reterive data
1. dml select statement reterive data1. dml select statement reterive data
1. dml select statement reterive data
Amrit Kaur
 
Sql commands
Sql commandsSql commands
Sql commands
Balakumaran Arunachalam
 
Sql wksht-6
Sql wksht-6Sql wksht-6
Sql wksht-6
Mukesh Tekwani
 
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)
Achmad Solichin
 
Oracle SQL DML Statements
Oracle SQL DML StatementsOracle SQL DML Statements
Oracle SQL DML Statements
A Data Guru
 
Sql
SqlSql
Sql
Diana Diana
 
Merging data (1)
Merging data (1)Merging data (1)
Merging data (1)
Ris Fernandez
 
The Database Environment Chapter 8
The Database Environment Chapter 8The Database Environment Chapter 8
The Database Environment Chapter 8
Jeanie Arnoco
 
SQL select statement and functions
SQL select statement and functionsSQL select statement and functions
SQL select statement and functions
Vikas Gupta
 
SQL Fundamentals
SQL FundamentalsSQL Fundamentals
SQL Fundamentals
Brian Foote
 
Module 3
Module 3Module 3
Module 3
cs19club
 
Chap 7
Chap 7Chap 7
Chap 7
Karan Patil
 
Ch04
Ch04Ch04
Ch04
cs19club
 
Ch05
Ch05Ch05
Ch05
cs19club
 

Viewers also liked (10)

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_presentation
Serafin 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's
Other Mother
 
Schizophrenia
SchizophreniaSchizophrenia
Schizophrenia
Schizophrenia 101
 
Lynching in america
Lynching in americaLynching in america
Lynching in america
Mohamed Taleb
 
PALEA
PALEAPALEA
PALEA
Sheila Dingcong
 
Printcatalog229594
Printcatalog229594Printcatalog229594
Printcatalog229594
ozwashroom
 
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
juanbtoribio
 
Courses
CoursesCourses
Courses
Paige Hannah
 
Robert koch
Robert kochRobert koch
Robert koch
shibushabeeb
 
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_presentation
Serafin 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's
Other Mother
 
Printcatalog229594
Printcatalog229594Printcatalog229594
Printcatalog229594
ozwashroom
 
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
juanbtoribio
 
Ad

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

DML Commands
DML CommandsDML Commands
DML Commands
Randy Riness @ South Puget Sound Community College
 
Sql (DBMS)
Sql (DBMS)Sql (DBMS)
Sql (DBMS)
Saransh Vijay
 
Ch 9 S Q L
Ch 9  S Q LCh 9  S Q L
Ch 9 S Q L
guest8fdbdd
 
Review of SQL
Review of SQLReview of SQL
Review of SQL
Information Technology
 
SQL Query
SQL QuerySQL Query
SQL Query
Imam340267
 
Modules 1basic-sql.ppt for engineering dbms
Modules 1basic-sql.ppt  for engineering dbmsModules 1basic-sql.ppt  for engineering dbms
Modules 1basic-sql.ppt for engineering dbms
chetanreddy2212
 
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
TheVerse1
 
Exploring collections with example
Exploring collections with exampleExploring collections with example
Exploring collections with example
pranav kumar verma
 
Creating database using sql commands
Creating database using sql commandsCreating database using sql commands
Creating database using sql commands
Belle Wx
 
chapter 8 SQL.ppt
chapter 8 SQL.pptchapter 8 SQL.ppt
chapter 8 SQL.ppt
YitbarekMurche
 
Query
QueryQuery
Query
Raj Devaraj
 
SQL
SQLSQL
SQL
Shyam Khant
 
SQL Overview
SQL OverviewSQL Overview
SQL Overview
Stewart Rogers
 
Lab
LabLab
Lab
neelam_rawat
 
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
Vaibhav Khanna
 
SQl data base management and design
SQl     data base management  and designSQl     data base management  and design
SQl data base management and design
franckelsania20
 
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...
SakkaravarthiS1
 
Database Architecture and Basic Concepts
Database Architecture and Basic ConceptsDatabase Architecture and Basic Concepts
Database Architecture and Basic Concepts
Tony Wong
 
asdasdasdasdsadasdasdasdasdsadasdasdasdsadsadasd
asdasdasdasdsadasdasdasdasdsadasdasdasdsadsadasdasdasdasdasdsadasdasdasdasdsadasdasdasdsadsadasd
asdasdasdasdsadasdasdasdasdsadasdasdasdsadsadasd
MuhamedAhmed35
 
Intro to tsql unit 9
Intro to tsql   unit 9Intro to tsql   unit 9
Intro to tsql unit 9
Syed Asrarali
 
Modules 1basic-sql.ppt for engineering dbms
Modules 1basic-sql.ppt  for engineering dbmsModules 1basic-sql.ppt  for engineering dbms
Modules 1basic-sql.ppt for engineering dbms
chetanreddy2212
 
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
TheVerse1
 
Exploring collections with example
Exploring collections with exampleExploring collections with example
Exploring collections with example
pranav kumar verma
 
Creating database using sql commands
Creating database using sql commandsCreating database using sql commands
Creating database using sql commands
Belle Wx
 
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
Vaibhav Khanna
 
SQl data base management and design
SQl     data base management  and designSQl     data base management  and design
SQl data base management and design
franckelsania20
 
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...
SakkaravarthiS1
 
Database Architecture and Basic Concepts
Database Architecture and Basic ConceptsDatabase Architecture and Basic Concepts
Database Architecture and Basic Concepts
Tony Wong
 
asdasdasdasdsadasdasdasdasdsadasdasdasdsadsadasd
asdasdasdasdsadasdasdasdasdsadasdasdasdsadsadasdasdasdasdasdsadasdasdasdasdsadasdasdasdsadsadasd
asdasdasdasdsadasdasdasdasdsadasdasdasdsadsadasd
MuhamedAhmed35
 
Intro to tsql unit 9
Intro to tsql   unit 9Intro to tsql   unit 9
Intro to tsql unit 9
Syed Asrarali
 
Ad

More from Ehtisham Ali (17)

Android tutorial
Android tutorialAndroid tutorial
Android tutorial
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-normailzation
Ehtisham Ali
 
Sql server ___________session2-data_modeling
Sql server  ___________session2-data_modelingSql server  ___________session2-data_modeling
Sql server ___________session2-data_modeling
Ehtisham 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-intro
Ehtisham 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 server
Ehtisham Ali
 
Sql server ___________data control language
Sql server  ___________data control languageSql server  ___________data control language
Sql server ___________data control language
Ehtisham Ali
 
Sql server ___________ (advance sql)
Sql server  ___________  (advance sql)Sql server  ___________  (advance sql)
Sql server ___________ (advance sql)
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-normailzation
Ehtisham Ali
 
Sql server ___________session2-data_modeling
Sql server  ___________session2-data_modelingSql server  ___________session2-data_modeling
Sql server ___________session2-data_modeling
Ehtisham 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-intro
Ehtisham 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 server
Ehtisham Ali
 
Sql server ___________data control language
Sql server  ___________data control languageSql server  ___________data control language
Sql server ___________data control language
Ehtisham Ali
 
Sql server ___________ (advance sql)
Sql server  ___________  (advance sql)Sql server  ___________  (advance sql)
Sql server ___________ (advance sql)
Ehtisham Ali
 

Recently uploaded (20)

The History of Kashmir Karkota Dynasty NEP.pptx
The History of Kashmir Karkota Dynasty NEP.pptxThe History of Kashmir Karkota Dynasty NEP.pptx
The History of Kashmir Karkota Dynasty NEP.pptx
Arya Mahila P. G. College, Banaras Hindu University, Varanasi, India.
 
Final Evaluation.docx...........................
Final Evaluation.docx...........................Final Evaluation.docx...........................
Final Evaluation.docx...........................
l1bbyburrell
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
Nguyen Thanh Tu Collection
 
How to Add Button in Chatter in Odoo 18 - Odoo Slides
How to Add Button in Chatter in Odoo 18 - Odoo SlidesHow to Add Button in Chatter in Odoo 18 - Odoo Slides
How to Add Button in Chatter in Odoo 18 - Odoo Slides
Celine George
 
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon DolabaniHistory Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
fruinkamel7m
 
Unit 5 ACUTE, SUBACUTE,CHRONIC TOXICITY.pptx
Unit 5 ACUTE, SUBACUTE,CHRONIC TOXICITY.pptxUnit 5 ACUTE, SUBACUTE,CHRONIC TOXICITY.pptx
Unit 5 ACUTE, SUBACUTE,CHRONIC TOXICITY.pptx
Mayuri Chavan
 
How To Maximize Sales Performance using Odoo 18 Diverse views in sales module
How To Maximize Sales Performance using Odoo 18 Diverse views in sales moduleHow To Maximize Sales Performance using Odoo 18 Diverse views in sales module
How To Maximize Sales Performance using Odoo 18 Diverse views in sales module
Celine George
 
Peer Assessment_ Unit 2 Skills Development for Live Performance - for Libby.docx
Peer Assessment_ Unit 2 Skills Development for Live Performance - for Libby.docxPeer Assessment_ Unit 2 Skills Development for Live Performance - for Libby.docx
Peer Assessment_ Unit 2 Skills Development for Live Performance - for Libby.docx
19lburrell
 
Search Matching Applicants in Odoo 18 - Odoo Slides
Search Matching Applicants in Odoo 18 - Odoo SlidesSearch Matching Applicants in Odoo 18 - Odoo Slides
Search Matching Applicants in Odoo 18 - Odoo Slides
Celine George
 
Pope Leo XIV, the first Pope from North America.pptx
Pope Leo XIV, the first Pope from North America.pptxPope Leo XIV, the first Pope from North America.pptx
Pope Leo XIV, the first Pope from North America.pptx
Martin M Flynn
 
2025 The Senior Landscape and SET plan preparations.pptx
2025 The Senior Landscape and SET plan preparations.pptx2025 The Senior Landscape and SET plan preparations.pptx
2025 The Senior Landscape and SET plan preparations.pptx
mansk2
 
How to Configure Public Holidays & Mandatory Days in Odoo 18
How to Configure Public Holidays & Mandatory Days in Odoo 18How to Configure Public Holidays & Mandatory Days in Odoo 18
How to Configure Public Holidays & Mandatory Days in Odoo 18
Celine George
 
TERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptx
TERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptxTERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptx
TERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptx
PoojaSen20
 
DEATH & ITS TYPES AND PHYSIOLOGICAL CHANGES IN BODY AFTER DEATH, PATIENT WILL...
DEATH & ITS TYPES AND PHYSIOLOGICAL CHANGES IN BODY AFTER DEATH, PATIENT WILL...DEATH & ITS TYPES AND PHYSIOLOGICAL CHANGES IN BODY AFTER DEATH, PATIENT WILL...
DEATH & ITS TYPES AND PHYSIOLOGICAL CHANGES IN BODY AFTER DEATH, PATIENT WILL...
PoojaSen20
 
ANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptx
ANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptxANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptx
ANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptx
Mayuri Chavan
 
E-Filing_of_Income_Tax.pptx and concept of form 26AS
E-Filing_of_Income_Tax.pptx and concept of form 26ASE-Filing_of_Income_Tax.pptx and concept of form 26AS
E-Filing_of_Income_Tax.pptx and concept of form 26AS
Abinash Palangdar
 
Look Up, Look Down: Spotting Local History Everywhere
Look Up, Look Down: Spotting Local History EverywhereLook Up, Look Down: Spotting Local History Everywhere
Look Up, Look Down: Spotting Local History Everywhere
History of Stoke Newington
 
Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...
Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...
Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...
parmarjuli1412
 
COPA Apprentice exam Questions and answers PDF
COPA Apprentice exam Questions and answers PDFCOPA Apprentice exam Questions and answers PDF
COPA Apprentice exam Questions and answers PDF
SONU HEETSON
 
"Heraldry Detective Project"- Coats of Arms and Mottos of "Ivanhoe" in Ivanho...
"Heraldry Detective Project"- Coats of Arms and Mottos of "Ivanhoe" in Ivanho..."Heraldry Detective Project"- Coats of Arms and Mottos of "Ivanhoe" in Ivanho...
"Heraldry Detective Project"- Coats of Arms and Mottos of "Ivanhoe" in Ivanho...
ruslana1975
 
Final Evaluation.docx...........................
Final Evaluation.docx...........................Final Evaluation.docx...........................
Final Evaluation.docx...........................
l1bbyburrell
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
Nguyen Thanh Tu Collection
 
How to Add Button in Chatter in Odoo 18 - Odoo Slides
How to Add Button in Chatter in Odoo 18 - Odoo SlidesHow to Add Button in Chatter in Odoo 18 - Odoo Slides
How to Add Button in Chatter in Odoo 18 - Odoo Slides
Celine George
 
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon DolabaniHistory Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
fruinkamel7m
 
Unit 5 ACUTE, SUBACUTE,CHRONIC TOXICITY.pptx
Unit 5 ACUTE, SUBACUTE,CHRONIC TOXICITY.pptxUnit 5 ACUTE, SUBACUTE,CHRONIC TOXICITY.pptx
Unit 5 ACUTE, SUBACUTE,CHRONIC TOXICITY.pptx
Mayuri Chavan
 
How To Maximize Sales Performance using Odoo 18 Diverse views in sales module
How To Maximize Sales Performance using Odoo 18 Diverse views in sales moduleHow To Maximize Sales Performance using Odoo 18 Diverse views in sales module
How To Maximize Sales Performance using Odoo 18 Diverse views in sales module
Celine George
 
Peer Assessment_ Unit 2 Skills Development for Live Performance - for Libby.docx
Peer Assessment_ Unit 2 Skills Development for Live Performance - for Libby.docxPeer Assessment_ Unit 2 Skills Development for Live Performance - for Libby.docx
Peer Assessment_ Unit 2 Skills Development for Live Performance - for Libby.docx
19lburrell
 
Search Matching Applicants in Odoo 18 - Odoo Slides
Search Matching Applicants in Odoo 18 - Odoo SlidesSearch Matching Applicants in Odoo 18 - Odoo Slides
Search Matching Applicants in Odoo 18 - Odoo Slides
Celine George
 
Pope Leo XIV, the first Pope from North America.pptx
Pope Leo XIV, the first Pope from North America.pptxPope Leo XIV, the first Pope from North America.pptx
Pope Leo XIV, the first Pope from North America.pptx
Martin M Flynn
 
2025 The Senior Landscape and SET plan preparations.pptx
2025 The Senior Landscape and SET plan preparations.pptx2025 The Senior Landscape and SET plan preparations.pptx
2025 The Senior Landscape and SET plan preparations.pptx
mansk2
 
How to Configure Public Holidays & Mandatory Days in Odoo 18
How to Configure Public Holidays & Mandatory Days in Odoo 18How to Configure Public Holidays & Mandatory Days in Odoo 18
How to Configure Public Holidays & Mandatory Days in Odoo 18
Celine George
 
TERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptx
TERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptxTERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptx
TERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptx
PoojaSen20
 
DEATH & ITS TYPES AND PHYSIOLOGICAL CHANGES IN BODY AFTER DEATH, PATIENT WILL...
DEATH & ITS TYPES AND PHYSIOLOGICAL CHANGES IN BODY AFTER DEATH, PATIENT WILL...DEATH & ITS TYPES AND PHYSIOLOGICAL CHANGES IN BODY AFTER DEATH, PATIENT WILL...
DEATH & ITS TYPES AND PHYSIOLOGICAL CHANGES IN BODY AFTER DEATH, PATIENT WILL...
PoojaSen20
 
ANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptx
ANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptxANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptx
ANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptx
Mayuri Chavan
 
E-Filing_of_Income_Tax.pptx and concept of form 26AS
E-Filing_of_Income_Tax.pptx and concept of form 26ASE-Filing_of_Income_Tax.pptx and concept of form 26AS
E-Filing_of_Income_Tax.pptx and concept of form 26AS
Abinash Palangdar
 
Look Up, Look Down: Spotting Local History Everywhere
Look Up, Look Down: Spotting Local History EverywhereLook Up, Look Down: Spotting Local History Everywhere
Look Up, Look Down: Spotting Local History Everywhere
History of Stoke Newington
 
Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...
Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...
Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...
parmarjuli1412
 
COPA Apprentice exam Questions and answers PDF
COPA Apprentice exam Questions and answers PDFCOPA Apprentice exam Questions and answers PDF
COPA Apprentice exam Questions and answers PDF
SONU HEETSON
 
"Heraldry Detective Project"- Coats of Arms and Mottos of "Ivanhoe" in Ivanho...
"Heraldry Detective Project"- Coats of Arms and Mottos of "Ivanhoe" in Ivanho..."Heraldry Detective Project"- Coats of Arms and Mottos of "Ivanhoe" in Ivanho...
"Heraldry Detective Project"- Coats of Arms and Mottos of "Ivanhoe" in Ivanho...
ruslana1975
 

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
  翻译: