SEGUNDA FASE / S2B MIC PERNAMBUCO
description
Transcript of SEGUNDA FASE / S2B MIC PERNAMBUCO
SE
GU
ND
A F
AS
E /
S2
B
MIC
PE
RN
AM
BU
CO
Banco de Dados
Turma: Manhã / FIRTurma: Manhã / FIRRecife-PERecife-PE
www.micpernambuco.com.br
FUNÇÕESFUNÇÕES
Criando uma função definida pelo usuário Definindo permissões para funções definidas
pelo usuário Alterando e descartando funções definidas
pelo usuário
FUNÇÕESFUNÇÕES
USE SupermercadoGOCREATE FUNCTION fn_VerificaValor (@valorentrada nvarchar(30)) RETURNS nvarchar(30)BEGIN IF @valorentrada IS NULL SET @valorentrada = ‘Valor nao aplicável.' RETURN @valorentradaEND
USE SupermercadoGOCREATE FUNCTION fn_VerificaValor (@valorentrada nvarchar(30)) RETURNS nvarchar(30)BEGIN IF @valorentrada IS NULL SET @valorentrada = ‘Valor nao aplicável.' RETURN @valorentradaEND
SELECT idProduto, dbo.fn_VerificaValor(QuantidadeVendida)FROM Vendas
SELECT idProduto, dbo.fn_VerificaValor(QuantidadeVendida)FROM Vendas
Função escalar:
Alterando funções
Mantém permissões atribuídasFaz com que a nova definição de função substitua
a definição existente Descartando funções
ALTER FUNCTION dbo.fn_VerificaValor <Novo conteúdo de função>
ALTER FUNCTION dbo.fn_VerificaValor <Novo conteúdo de função>
DROP FUNCTION dbo.fn_VerificaValorDROP FUNCTION dbo.fn_VerificaValor
FUNÇÕESFUNÇÕES
A cláusula RETURNS especifica o tipo de dados
A função é definida em um bloco BEGIN...END
O tipo de retorno poderá ser qualquer tipo de dado, exceto text, ntext, image, cursor ou timestamp
FUNÇÕESFUNÇÕES
USE BancoGOCREATE FUNCTION fn_ExibeEstado ( @Nome nvarchar(30) )RETURNS tableASRETURN ( SELECT ID_Estado, NomeEstado, DescricaoEstado FROM Banco.dbo.Estados WHERE NomeEstado = @Nome )
USE BancoGOCREATE FUNCTION fn_ExibeEstado ( @Nome nvarchar(30) )RETURNS tableASRETURN ( SELECT ID_Estado, NomeEstado, DescricaoEstado FROM Banco.dbo.Estados WHERE NomeEstado = @Nome )
FUNÇÕESFUNÇÕES
SELECT * FROM fn_ExibeEstado(‘Pernambuco’) SELECT * FROM fn_ExibeEstado(‘Pernambuco’)
Função in-line:
Associados a uma tabela Chamados automaticamente Não podem ser chamados diretamente É parte de uma transação
TRIGGERS (DISPARADORES)TRIGGERS (DISPARADORES)
TRIGGERS (DISPARADORES)TRIGGERS (DISPARADORES)
Requer permissões apropriadas Não pode conter certas instruções
Use [Banco de uma empresa]GOCREATE TRIGGER AoApagarFuncionario ON FuncionariosFOR DELETE ASIF (SELECT COUNT(*) FROM Deleted) > 1BEGIN RAISERROR( ‘Você não pode apagar mais de um funcionário ao mesmo tempo.', 16, 1) ROLLBACK TRANSACTIONEND
Use [Banco de uma empresa]GOCREATE TRIGGER AoApagarFuncionario ON FuncionariosFOR DELETE ASIF (SELECT COUNT(*) FROM Deleted) > 1BEGIN RAISERROR( ‘Você não pode apagar mais de um funcionário ao mesmo tempo.', 16, 1) ROLLBACK TRANSACTIONEND
Alterando um disparadorAltera a definição sem descartar o disparador
USE NorthwindGOALTER TRIGGER Empl_Delete ON EmployeesFOR DELETE ASIF (SELECT COUNT(*) FROM Deleted) > 6BEGIN RAISERROR( 'You cannot delete more than six employees at a time.', 16, 1) ROLLBACK TRANSACTIONEND
USE NorthwindGOALTER TRIGGER Empl_Delete ON EmployeesFOR DELETE ASIF (SELECT COUNT(*) FROM Deleted) > 6BEGIN RAISERROR( 'You cannot delete more than six employees at a time.', 16, 1) ROLLBACK TRANSACTIONEND
TRIGGERS (DISPARADORES)TRIGGERS (DISPARADORES)
Como funciona um disparador INSERT Como funciona um disparador DELETE Como funciona um disparador UPDATE
TRIGGERS (DISPARADORES)TRIGGERS (DISPARADORES)
Instrução INSERT para uma tabela com um disparador INSERT definido
INSERT [Order Details] VALUES(10525, 2, 19.00, 5, 0.2)INSERT [Order Details] VALUES(10525, 2, 19.00, 5, 0.2)
Order DetailsOrder DetailsOrder DetailsOrder Details
OrderIDOrderID
105221052310524
105221052310524
ProductIDProductID
10417
10417
UnitPriceUnitPrice
31.009.6530.00
31.009.6530.00
QuantityQuantity
7924
7924
DiscountDiscount
0.20.150.0
0.20.150.0
Instrução INSERT registrada
insertedinsertedinsertedinserted
1052310523 22 19.0019.00 55 0.20.2
5 19.002 0.210523
As ações de TRIGGER são executadas
Order DetailsOrder DetailsOrder DetailsOrder Details
OrderIDOrderID
105221052310524
105221052310524
ProductIDProductID
10417
10417
UnitPriceUnitPrice
31.009.6530.00
31.009.6530.00
QuantityQuantity
7924
7924
DiscountDiscount
0.20.150.0
0.20.150.0
5 19.002 0.210523
Trigger Code:USE NorthwindCREATE TRIGGER OrdDet_InsertON [Order Details]FOR INSERTASUPDATE P SET UnitsInStock = (P.UnitsInStock – I.Quantity)FROM Products AS P INNER JOIN Inserted AS ION P.ProductID = I.ProductID
Trigger Code:USE NorthwindCREATE TRIGGER OrdDet_InsertON [Order Details]FOR INSERTASUPDATE P SET UnitsInStock = (P.UnitsInStock – I.Quantity)FROM Products AS P INNER JOIN Inserted AS ION P.ProductID = I.ProductID
ProdutosProdutosProdutosProdutos
ProductIDProductID UnitsInStockUnitsInStock …… ……
1234
1234
15106520
15106520
2 15
UPDATE P SET UnitsInStock = (P.UnitsInStock – I.Quantity)FROM Products AS P INNER JOIN Inserted AS ION P.ProductID = I.ProductID
Instrução INSERT para uma tabela com umdisparador INSERT definido
Instrução INSERT registrada
Ações de disparador executadas
1111
2222
3333
TRIGGERS (DISPARADORES)TRIGGERS (DISPARADORES)
Instrução DELETE para uma tabela com um disparadorDELETE definido
DeletedDeletedDeletedDeleted
44 Dairy ProductsDairy Products CheesesCheeses 0x15…0x15…
Instrução DELETE registrada
CategoriesCategoriesCategoriesCategories
CategoryIDCategoryID
123
123
CategoryNameCategoryName
BeveragesCondimentsConfections
BeveragesCondimentsConfections
DescriptionDescription
Soft drinks, coffees…Sweet and savory …Desserts, candies, …
Soft drinks, coffees…Sweet and savory …Desserts, candies, …
PicturePicture
0x15…0x15…0x15…
0x15…0x15…0x15… 0x15…CheesesDairy Products4
DELETE CategoriesWHERE CategoryID = 4
DELETE CategoriesWHERE CategoryID = 4
USE NorthwindCREATE TRIGGER Category_Delete
ON CategoriesFOR DELETE
ASUPDATE P SET Discontinued = 1FROM Products AS P INNER JOIN deleted AS dON P.CategoryID = d.CategoryID
USE NorthwindCREATE TRIGGER Category_Delete
ON CategoriesFOR DELETE
ASUPDATE P SET Discontinued = 1FROM Products AS P INNER JOIN deleted AS dON P.CategoryID = d.CategoryID
Ações de disparador executadas
ProductsProductsProductsProducts
ProductIDProductID DiscontinuedDiscontinued …… ……
1234
1234
0000
0000
2 1
UPDATE P SET Discontinued = 1FROM Products AS P INNER JOIN deleted AS dON P.CategoryID = d.CategoryID
Instrução DELETE para uma tabela com um disparador DELETE definido
Instrução DELETE registrada
Ações de disparador executadas
1111
2222
3333
TRIGGERS (DISPARADORES)TRIGGERS (DISPARADORES)
Instrução UPDATE para uma tabela com um disparador UPDATE definido
UPDATE EmployeesSET EmployeeID = 17WHERE EmployeeID = 2
UPDATE EmployeesSET EmployeeID = 17WHERE EmployeeID = 2
Instrução UPDATE registrada como INSERT e instruções DELETE
insertedinsertedinsertedinserted
1717 FullerFuller AndrewAndrew Vice Pres.Vice Pres. ~~~~~~
deleteddeleteddeleteddeleted
22 FullerFuller AndrewAndrew Vice Pres.Vice Pres. ~~~~~~
EmployeesEmployeesEmployeesEmployees
EmployeeIDEmployeeID LastNameLastName FirstNameFirstName TitleTitle HireDateHireDate
1234
1234
DavolioBarrLeverlingPeacock
DavolioBarrLeverlingPeacock
NancyAndrewJanetMargaret
NancyAndrewJanetMargaret
Sales Rep.RSales Rep.Sales Rep.
Sales Rep.RSales Rep.Sales Rep.
~~~~~~~~~~~~
~~~~~~~~~~~~
2 Fuller Andrew Vice Pres. ~~~
As ações de TRIGGER são executadas
USE NorthwindGOCREATE TRIGGER Employee_Update
ON EmployeesFOR UPDATE
ASIF UPDATE (EmployeeID)BEGIN TRANSACTION
RAISERROR ('Transaction cannot be processed.\***** Employee ID number cannot be modified.', 10, 1)ROLLBACK TRANSACTION
USE NorthwindGOCREATE TRIGGER Employee_Update
ON EmployeesFOR UPDATE
ASIF UPDATE (EmployeeID)BEGIN TRANSACTION
RAISERROR ('Transaction cannot be processed.\***** Employee ID number cannot be modified.', 10, 1)ROLLBACK TRANSACTION
ASIF UPDATE (EmployeeID)BEGIN TRANSACTIONRAISERROR ('Transaction cannot be processed.\***** Employee ID number cannot be modified.', 10, 1)ROLLBACK TRANSACTION
Transaction cannot be processed. ***** Member number cannot be modified Transaction cannot be processed. ***** Member number cannot be modified
EmployeesEmployeesEmployeesEmployees
EmployeeIDEmployeeID LastNameLastName FirstNameFirstName TitleTitle HireDateHireDate
1234
1234
DavolioBarrLeverlingPeacock
DavolioBarrLeverlingPeacock
NancyAndrewJanetMargaret
NancyAndrewJanetMargaret
Sales Rep.RSales Rep.Sales Rep.
Sales Rep.RSales Rep.Sales Rep.
~~~~~~~~~~~~
~~~~~~~~~~~~
2 Fuller Andrew Vice Pres. ~~~
Instrução UPDATE para uma tabela com um disparador UPDATE definido
Instrução UPDATE registrada com instruções INSERT e DELETE
Ações de disparador executadas
1111
2222
3333
TRIGGERS (DISPARADORES)TRIGGERS (DISPARADORES)
Impondo a integridade dos dados
CREATE TRIGGER BackOrderList_Delete ON Products FOR UPDATEASIF (SELECT BO.ProductID FROM BackOrders AS BO JOIN Inserted AS I ON BO.ProductID = I.Product_ID ) > 0BEGIN DELETE BO FROM BackOrders AS BO INNER JOIN Inserted AS I ON BO.ProductID = I.ProductIDEND
CREATE TRIGGER BackOrderList_Delete ON Products FOR UPDATEASIF (SELECT BO.ProductID FROM BackOrders AS BO JOIN Inserted AS I ON BO.ProductID = I.Product_ID ) > 0BEGIN DELETE BO FROM BackOrders AS BO INNER JOIN Inserted AS I ON BO.ProductID = I.ProductIDEND
ProductsProductsProductsProducts
ProductIDProductID UnitsInStockUnitsInStock …… ……
1
34
1
34
15106520
15106520
2 15 AtualizadoAtualizado
BackOrdersBackOrdersBackOrdersBackOrders
ProductIDProductID UnitsOnOrderUnitsOnOrder ……
1123
1123
151065
151065
2 15 O disparador
exclui o registroO disparador
exclui o registro
TRIGGERS (DISPARADORES)TRIGGERS (DISPARADORES)
Considerações sobre o desempenho
Os disparadores funcionam com rapidez, pois as tabelas Inserted e Deleted encontram-se no cache
O tempo de execução é determinado pelo:Número de tabelas referenciadasNúmero de registros afetados
As ações contidas nos disparadores consistem em uma parte implícita de uma transação
TRIGGERS (DISPARADORES)TRIGGERS (DISPARADORES)