SlideShare a Scribd company logo
eleks.com
• CTE
• DML оператори
• Представлення
Data Manipulation Language
Views
Common Table Expression
Конструкція Common Table Expression (CTE):
;with ActorsAndGenres as
(
select a.Name, g.Name as Genre
from Actor a
inner join [Cast] c on c.ActorId = a.ActorId
inner join Movie m on m.MovieId = c.MovieId
inner join Genre g on m.GenreKey = g.GenreKey
group by a.Name, g.Name
)
select Name from ActorsAndGenres
where Genre = 'Thriller'
union
select Name from ActorsAndGenres
where Genre = 'Horror'
Рекурсивні CTE
Генерація числової послідовності:
;with Numbers as
(
select 1 as n
union all
select n + 1
from Numbers
where n + 1 <= 10
)
select n
from Numbers
Отримання вузлів дерева:
;with pathToRoot as
(
select NodeId, ParentNodeId from Node
where NodeId = 42
union all
select n.NodeId, n.ParentNodeId from Node n
inner join pathToRoot r
on r.ParentNodeID = n.NodeID
)
select NodeId, ParentNodeId
from pathToRoot
Data Manipulation Language
• INSERT - вставка нового рядка або набору рядків в
таблицю БД
• UPDATE - зміна даних в таблиці БД
• DELETE - видалення рядка або набору рядків із
таблиці БД
• MERGE – всі операції над даними в одному виразі
• TRUNCATE – Очистка таблиці
Оператор INSERT
Вставка одного рядка з явно заданими значеннями:
insert into Actor(Name, BirthDate, SexEnum)
values (‘Jack Nickolson', ‘1937-04-25’, 1)
Використання опції DEFAULT:
CREATE TABLE Document (
…
Date datetime NOT NULL DEFAULT getdate(),
…
insert into Document (Type, Number, Client, Amount)
values (1, 'Z-001', 1, 10)
insert into Document (Type, Number, Date, Client, Amount)
values (1, 'Z-003', default, 1, 10)
insert into Document DEFAULT VALUES
Оператор INSERT
Вставка більше одного рядка :
insert into Document (Type, Number, Date, Client, Amount)
select 1, 'Z-010', getdate(), 1, 10
union all
select 1, 'Z-011', cast('2007-10-30' as datetime), 2, 10
insert into Document (Type, Number, Date, Client, Amount)
select Type, 'Z-012', Date, Client, Amount
from Document where Number = 'Z-003‘
insert into Actor (Name, Age, SexEnum)
values
('Jack Nicholson', '1937-04-25', 1)
,('Ralph Fiennes', '1969-03-12', 1)
,('Robert De Niro', '1943-08-01', 1)
Оператор INSERT
Автоінкремент (IDENTITY):
insert into Document (Type, Number, Date, Client, Amount)
select 1, 'Z-005', getdate(), 1, 10
select SCOPE_IDENTITY()
Вставка в такий стовпчик заборонена, видається повідомлення про
помилку.
Включити додавання даних до стовпців з автоінкрементом:
SET IDENTITY_INSERT Document ON/OFF
Оператор UPDATE
Змінює наявні дані:
update Document
set
Date = default
,Comment = NULL
where DocumentId = 1
Використання підзапитів та функцій:
update Document
set
Amount = (select sum(Amount*Price) from DocumentDetail
where Number = DocumentDetail)
,Comment = case
when Comment is null then ''
else left( Comment, 10)
end
where DocumentId = 1
Оператор UPDATE
Запити з кількох таблиць при зміні даних:
update doc
set Comment = 'Client - ' + Name
from Document doc
inner join Client c
on cInstance = dClient
Можна міняти дані лише в одній таблиці одночасно.
Без використання WHERE оператор UPDATE змінить всі рядки в таблиці
Видалення даних
Оператор DELETE:
delete from Document
where Number > 'Z'
Команда TRUNCATE:
truncate table [Cast]
Відмінності використання TRUNCATE та DELETE :
 Не логується видалення окремих рядків таблиці, записуються лише відомості
про звільнений простір
 Не обробляються трігери та, як наслідок, посилання на зовнішні ключі
 Значення автогенератора (IDENTITY) змінюється на початкове
 Потрібно мати доступ до таблиці як власник
Як і у випадку з UPDATE:
не забувайте WHERE =)
Оператор MERGE
Вся логіка роботи з таблицею в одному операторі:
;merge into dbo.LayerBuffer as target
using @LayerBuffers as source
on (target.LayerBufferId = source.LayerBufferId)
when matched then
update set target.Argb = source.Argb
when not matched by source and (target.LayerId = @LayerId) then
delete
when not matched by target then
insert (LayerId, BufferMeters, Shape)
values (
@LayerId
,source.BufferMeters
,source.Shape)
);
Оператор OUTPUT
Вивід змінених значень:
insert into Movie
(Name, Description, PremiereDate, BoxOffice, GenreKey)
output inserted.MovieId, inserted.Name
values
('Pulp Fiction', null, '1994-02-22', 21349700, 7)
,('The Shining', null, '1980-05-23', 30000400, 13)
update [Cast]
set CharacterName = ‘Willy Wonka’
output inserted.CharacterName into #tempTable
where CharacterName = ‘WalterWhite’
delete from Feedback
output deleted.FeedbackId into DeletedId(Id)
where Rank < 5
OUTPUT та MERGE
;with newActor as (
select 'Natalie Portman' Name
union select 'Jack Nicholson'
union select 'Tom Hanks'
)
merge into Actor as target
using newActor as source
on (target.Name = source.Name)
when matched then
update set BirthDate = ‘1753-01-01'
when not matched by source then
delete
when not matched by target then
insert (Name, BirthDate, SexEnum)
values(source.Name, source.BirthDate, source.SexEnum)
output $action, inserted.ActorId, inserted.Name, deleted.ActorId,
deleted.Name;
OUTPUT та MERGE
Мапінг значень з різних таблиць:
merge into dbo.[Event] using @Events as e on 1 = 0
when not matched then
insert
(
Name,
Description
)
values
(
Name,
Description
)
output e.FakeEventId, inserted.EventId
into RealAndFakeIds (fakeId, realId);
Представлення View
Створення представлень:
create view DocumentView as
select d.DocumentId, d.Name, t.Type, d.Number, d.Date, d.Amount
from Document d
inner join Client c on c.ClientId = d.ClientId
inner join DocumentType t on t.DocumentTypeId = d.DocumentTypeId
При створенні представлень можна вказати додаткові опції, наприклад, WITH CHECK OPTION чи
WITH ENCRYPTION, інші.
Використання представлень:
select * from DocumentView
DocumentId Name Type Number Date Amount
--------- --------- ------- ------- ---------- -------
1 Client_1 Invoice I-001 2007-10-31 0.00
2 Client_2 Invoice I-002 2007-01-04 35.00
3 Client_1 Invoice I-003 2007-02-04 10.00
4 Client_1 Invoice I-004 2007-02-04 20.00
Зміна даних за допомогою представлень:
INSERT INTO DocumentView(Name) VALUES ('AAA')
update DocumentView
set Date = cast(convert(varchar(10), Date, 102) as datetime)
Дані в представленнях можна змінювати прямо вказані поля із
таблиць за допомогою операторів INSERT, UPDATE, DELETE лише в
одній табличці одночасно та при виконанні наступних умов :
― відсутність агрегатних функцій та виразу GROUP BY
― не можна використовувати CROSS JOIN
― відсутність виразів TOP, DISTINCT чи UNION
― не можна використовувати колонки, які обраховуються всередині
представлення
Представлення View
Sql 04n edited

More Related Content

Viewers also liked

DAL
DALDAL
Frontend basics
Frontend basicsFrontend basics
Frontend basics
eleksdev
 
Rpc
RpcRpc
Windows service
Windows serviceWindows service
Windows service
eleksdev
 
Advanced styles
Advanced stylesAdvanced styles
Advanced styles
eleksdev
 
SDLC. PM Role
SDLC. PM RoleSDLC. PM Role
SDLC. PM Role
eleksdev
 
Angular. presentation
Angular. presentationAngular. presentation
Angular. presentation
eleksdev
 
NoSQL basics
NoSQL basicsNoSQL basics
NoSQL basics
eleksdev
 
Aspnet core
Aspnet coreAspnet core
Aspnet core
eleksdev
 
Continuous Delivery concept overview. Continuous Integration Systems. DevOps ...
Continuous Delivery concept overview. Continuous Integration Systems. DevOps ...Continuous Delivery concept overview. Continuous Integration Systems. DevOps ...
Continuous Delivery concept overview. Continuous Integration Systems. DevOps ...
eleksdev
 
sql introduction
sql introductionsql introduction
sql introduction
eleksdev
 
G rpc lection1
G rpc lection1G rpc lection1
G rpc lection1
eleksdev
 
G rpc lection1_theory_bkp2
G rpc lection1_theory_bkp2G rpc lection1_theory_bkp2
G rpc lection1_theory_bkp2
eleksdev
 
SDLC. BA Role
SDLC. BA RoleSDLC. BA Role
SDLC. BA Role
eleksdev
 
SDLC. UX Role
SDLC. UX RoleSDLC. UX Role
SDLC. UX Role
eleksdev
 
#2 integration + ui tests
#2 integration + ui tests#2 integration + ui tests
#2 integration + ui tests
eleksdev
 
Code Practices
Code PracticesCode Practices
Code Practices
eleksdev
 
Advanced c sharp part 3
Advanced c sharp part 3Advanced c sharp part 3
Advanced c sharp part 3
eleksdev
 
If unit2 summary
If unit2 summaryIf unit2 summary
If unit2 summary
eleksdev
 
Mvvw patterns
Mvvw patternsMvvw patterns
Mvvw patterns
eleksdev
 

Viewers also liked (20)

DAL
DALDAL
DAL
 
Frontend basics
Frontend basicsFrontend basics
Frontend basics
 
Rpc
RpcRpc
Rpc
 
Windows service
Windows serviceWindows service
Windows service
 
Advanced styles
Advanced stylesAdvanced styles
Advanced styles
 
SDLC. PM Role
SDLC. PM RoleSDLC. PM Role
SDLC. PM Role
 
Angular. presentation
Angular. presentationAngular. presentation
Angular. presentation
 
NoSQL basics
NoSQL basicsNoSQL basics
NoSQL basics
 
Aspnet core
Aspnet coreAspnet core
Aspnet core
 
Continuous Delivery concept overview. Continuous Integration Systems. DevOps ...
Continuous Delivery concept overview. Continuous Integration Systems. DevOps ...Continuous Delivery concept overview. Continuous Integration Systems. DevOps ...
Continuous Delivery concept overview. Continuous Integration Systems. DevOps ...
 
sql introduction
sql introductionsql introduction
sql introduction
 
G rpc lection1
G rpc lection1G rpc lection1
G rpc lection1
 
G rpc lection1_theory_bkp2
G rpc lection1_theory_bkp2G rpc lection1_theory_bkp2
G rpc lection1_theory_bkp2
 
SDLC. BA Role
SDLC. BA RoleSDLC. BA Role
SDLC. BA Role
 
SDLC. UX Role
SDLC. UX RoleSDLC. UX Role
SDLC. UX Role
 
#2 integration + ui tests
#2 integration + ui tests#2 integration + ui tests
#2 integration + ui tests
 
Code Practices
Code PracticesCode Practices
Code Practices
 
Advanced c sharp part 3
Advanced c sharp part 3Advanced c sharp part 3
Advanced c sharp part 3
 
If unit2 summary
If unit2 summaryIf unit2 summary
If unit2 summary
 
Mvvw patterns
Mvvw patternsMvvw patterns
Mvvw patterns
 

More from eleksdev

Lecture android best practices
Lecture   android best practicesLecture   android best practices
Lecture android best practices
eleksdev
 
Communication in android
Communication in androidCommunication in android
Communication in android
eleksdev
 
Hello android world
Hello android worldHello android world
Hello android world
eleksdev
 
Android location and sensors API
Android location and sensors APIAndroid location and sensors API
Android location and sensors API
eleksdev
 
Lecture java basics
Lecture   java basicsLecture   java basics
Lecture java basics
eleksdev
 
Css animation, html5 api
Css animation, html5 apiCss animation, html5 api
Css animation, html5 api
eleksdev
 
Uml
UmlUml

More from eleksdev (7)

Lecture android best practices
Lecture   android best practicesLecture   android best practices
Lecture android best practices
 
Communication in android
Communication in androidCommunication in android
Communication in android
 
Hello android world
Hello android worldHello android world
Hello android world
 
Android location and sensors API
Android location and sensors APIAndroid location and sensors API
Android location and sensors API
 
Lecture java basics
Lecture   java basicsLecture   java basics
Lecture java basics
 
Css animation, html5 api
Css animation, html5 apiCss animation, html5 api
Css animation, html5 api
 
Uml
UmlUml
Uml
 

Sql 04n edited

  • 1. eleks.com • CTE • DML оператори • Представлення Data Manipulation Language Views
  • 2. Common Table Expression Конструкція Common Table Expression (CTE): ;with ActorsAndGenres as ( select a.Name, g.Name as Genre from Actor a inner join [Cast] c on c.ActorId = a.ActorId inner join Movie m on m.MovieId = c.MovieId inner join Genre g on m.GenreKey = g.GenreKey group by a.Name, g.Name ) select Name from ActorsAndGenres where Genre = 'Thriller' union select Name from ActorsAndGenres where Genre = 'Horror'
  • 3. Рекурсивні CTE Генерація числової послідовності: ;with Numbers as ( select 1 as n union all select n + 1 from Numbers where n + 1 <= 10 ) select n from Numbers Отримання вузлів дерева: ;with pathToRoot as ( select NodeId, ParentNodeId from Node where NodeId = 42 union all select n.NodeId, n.ParentNodeId from Node n inner join pathToRoot r on r.ParentNodeID = n.NodeID ) select NodeId, ParentNodeId from pathToRoot
  • 4. Data Manipulation Language • INSERT - вставка нового рядка або набору рядків в таблицю БД • UPDATE - зміна даних в таблиці БД • DELETE - видалення рядка або набору рядків із таблиці БД • MERGE – всі операції над даними в одному виразі • TRUNCATE – Очистка таблиці
  • 5. Оператор INSERT Вставка одного рядка з явно заданими значеннями: insert into Actor(Name, BirthDate, SexEnum) values (‘Jack Nickolson', ‘1937-04-25’, 1) Використання опції DEFAULT: CREATE TABLE Document ( … Date datetime NOT NULL DEFAULT getdate(), … insert into Document (Type, Number, Client, Amount) values (1, 'Z-001', 1, 10) insert into Document (Type, Number, Date, Client, Amount) values (1, 'Z-003', default, 1, 10) insert into Document DEFAULT VALUES
  • 6. Оператор INSERT Вставка більше одного рядка : insert into Document (Type, Number, Date, Client, Amount) select 1, 'Z-010', getdate(), 1, 10 union all select 1, 'Z-011', cast('2007-10-30' as datetime), 2, 10 insert into Document (Type, Number, Date, Client, Amount) select Type, 'Z-012', Date, Client, Amount from Document where Number = 'Z-003‘ insert into Actor (Name, Age, SexEnum) values ('Jack Nicholson', '1937-04-25', 1) ,('Ralph Fiennes', '1969-03-12', 1) ,('Robert De Niro', '1943-08-01', 1)
  • 7. Оператор INSERT Автоінкремент (IDENTITY): insert into Document (Type, Number, Date, Client, Amount) select 1, 'Z-005', getdate(), 1, 10 select SCOPE_IDENTITY() Вставка в такий стовпчик заборонена, видається повідомлення про помилку. Включити додавання даних до стовпців з автоінкрементом: SET IDENTITY_INSERT Document ON/OFF
  • 8. Оператор UPDATE Змінює наявні дані: update Document set Date = default ,Comment = NULL where DocumentId = 1 Використання підзапитів та функцій: update Document set Amount = (select sum(Amount*Price) from DocumentDetail where Number = DocumentDetail) ,Comment = case when Comment is null then '' else left( Comment, 10) end where DocumentId = 1
  • 9. Оператор UPDATE Запити з кількох таблиць при зміні даних: update doc set Comment = 'Client - ' + Name from Document doc inner join Client c on cInstance = dClient Можна міняти дані лише в одній таблиці одночасно. Без використання WHERE оператор UPDATE змінить всі рядки в таблиці
  • 10. Видалення даних Оператор DELETE: delete from Document where Number > 'Z' Команда TRUNCATE: truncate table [Cast] Відмінності використання TRUNCATE та DELETE :  Не логується видалення окремих рядків таблиці, записуються лише відомості про звільнений простір  Не обробляються трігери та, як наслідок, посилання на зовнішні ключі  Значення автогенератора (IDENTITY) змінюється на початкове  Потрібно мати доступ до таблиці як власник Як і у випадку з UPDATE: не забувайте WHERE =)
  • 11. Оператор MERGE Вся логіка роботи з таблицею в одному операторі: ;merge into dbo.LayerBuffer as target using @LayerBuffers as source on (target.LayerBufferId = source.LayerBufferId) when matched then update set target.Argb = source.Argb when not matched by source and (target.LayerId = @LayerId) then delete when not matched by target then insert (LayerId, BufferMeters, Shape) values ( @LayerId ,source.BufferMeters ,source.Shape) );
  • 12. Оператор OUTPUT Вивід змінених значень: insert into Movie (Name, Description, PremiereDate, BoxOffice, GenreKey) output inserted.MovieId, inserted.Name values ('Pulp Fiction', null, '1994-02-22', 21349700, 7) ,('The Shining', null, '1980-05-23', 30000400, 13) update [Cast] set CharacterName = ‘Willy Wonka’ output inserted.CharacterName into #tempTable where CharacterName = ‘WalterWhite’ delete from Feedback output deleted.FeedbackId into DeletedId(Id) where Rank < 5
  • 13. OUTPUT та MERGE ;with newActor as ( select 'Natalie Portman' Name union select 'Jack Nicholson' union select 'Tom Hanks' ) merge into Actor as target using newActor as source on (target.Name = source.Name) when matched then update set BirthDate = ‘1753-01-01' when not matched by source then delete when not matched by target then insert (Name, BirthDate, SexEnum) values(source.Name, source.BirthDate, source.SexEnum) output $action, inserted.ActorId, inserted.Name, deleted.ActorId, deleted.Name;
  • 14. OUTPUT та MERGE Мапінг значень з різних таблиць: merge into dbo.[Event] using @Events as e on 1 = 0 when not matched then insert ( Name, Description ) values ( Name, Description ) output e.FakeEventId, inserted.EventId into RealAndFakeIds (fakeId, realId);
  • 15. Представлення View Створення представлень: create view DocumentView as select d.DocumentId, d.Name, t.Type, d.Number, d.Date, d.Amount from Document d inner join Client c on c.ClientId = d.ClientId inner join DocumentType t on t.DocumentTypeId = d.DocumentTypeId При створенні представлень можна вказати додаткові опції, наприклад, WITH CHECK OPTION чи WITH ENCRYPTION, інші. Використання представлень: select * from DocumentView DocumentId Name Type Number Date Amount --------- --------- ------- ------- ---------- ------- 1 Client_1 Invoice I-001 2007-10-31 0.00 2 Client_2 Invoice I-002 2007-01-04 35.00 3 Client_1 Invoice I-003 2007-02-04 10.00 4 Client_1 Invoice I-004 2007-02-04 20.00
  • 16. Зміна даних за допомогою представлень: INSERT INTO DocumentView(Name) VALUES ('AAA') update DocumentView set Date = cast(convert(varchar(10), Date, 102) as datetime) Дані в представленнях можна змінювати прямо вказані поля із таблиць за допомогою операторів INSERT, UPDATE, DELETE лише в одній табличці одночасно та при виконанні наступних умов : ― відсутність агрегатних функцій та виразу GROUP BY ― не можна використовувати CROSS JOIN ― відсутність виразів TOP, DISTINCT чи UNION ― не можна використовувати колонки, які обраховуються всередині представлення Представлення View