Você está na página 1de 117

Bases de Dados II ISEP _________________________________________________________________________________________

1 INTRODUO ............................................................................................................................................... 3 1.1 SEGURANA ................................................................................................................................................ 3 1.1.1 Tipos de Autenticao ......................................................................................................................... 3 1.1.2 Roles .................................................................................................................................................... 3 1.1.3 Logins .................................................................................................................................................. 3 1.1.4 Users .................................................................................................................................................... 4 1.2 ACESSO AO SQL SERVER ............................................................................................................................ 4 1.2.1 Database API....................................................................................................................................... 4 1.3 SERVIOS SQLSERVER (WINDOWS NT) ..................................................................................................... 4 1.3.1 MSSQLServer ...................................................................................................................................... 4 1.3.2 SQLServerAgent .................................................................................................................................. 5 1.3.3 MSDTC (Distributed Transaction Coordinator) ................................................................................. 5 1.4 ARQUITECTURA DA BASE DE DADOS NO SQL SERVER ................................................................................. 6 1.4.1 Arquitectura lgica .............................................................................................................................. 6 1.4.2 Arquitectura fsica ............................................................................................................................... 6 Page .............................................................................................................................................................. 6 1.4 BASES DE DADOS DO SISTEMA ................................................................................................................... 11 1.4.1 Master ................................................................................................................................................ 11 1.4.2 Model ................................................................................................................................................. 12 1.4.3 Tempdb .............................................................................................................................................. 12 1.4.4 Msdb .................................................................................................................................................. 13 1.5 TABELAS DO SISTEMA................................................................................................................................ 13 1.6 DATABASE FILES ....................................................................................................................................... 13 1.6.1 Data files ........................................................................................................................................... 13 1.6.2 Nomes de ficheiros no SQL Server .................................................................................................... 14 2. INTRODUO AO TRANSACT-SQL ..................................................................................................... 15 2.1 DCL DATA CONTROL LANGUAGE .......................................................................................................... 15 2.1.1 Syntax da instruo Grant ................................................................................................................. 15 2.1.2 Syntax da instruo Deny .................................................................................................................. 17 2.1.3 Syntax da instruo Revoke ............................................................................................................... 18 2.2 DDL DATA DEFINITION LANGUAGE ....................................................................................................... 19 2.3 DML DATA MANIPULATION LANGUAGE................................................................................................ 19 2.4 VARIVEIS, OPERADORES, FUNES E INSTRUES DE CONTROLO ........................................................... 19 2.4.1 Variveis ............................................................................................................................................ 19 2.4.2 Operadores ........................................................................................................................................ 23 2.4.3 Funes ............................................................................................................................................. 25 2.4.4 Elementos de controlo ....................................................................................................................... 28 2.5 MODOS DE EXECUO DO T-SQL ............................................................................................................. 29 2.5.1 T-SQL Dinmico ................................................................................................................................ 29 2.5.2 Batch .................................................................................................................................................. 29 2.5.3 Scripts ................................................................................................................................................ 30 2.5.4 Transaes......................................................................................................................................... 30 3. CRIAO DA BD ........................................................................................................................................ 31 3.1 INTRODUO ............................................................................................................................................. 31 3.2 CRIAR, ALTERAR E APAGAR UMA BD ........................................................................................................ 31 3.2 TIPOS DE DADOS ........................................................................................................................................ 35 3.2.1 Tipo de dados pr-definidos .............................................................................................................. 35 3.2.2 Tipo de dados definidos pelo utilizador............................................................................................. 36 3.3 TABELAS ................................................................................................................................................... 37 3.3.1 Criar, alterar e apagar tabelas ......................................................................................................... 37 3.4 INTEGRIDADE DA BD ................................................................................................................................. 43 3.4.1 Tipos de integridade .......................................................................................................................... 43 3.4.2 Definio de Constraints ................................................................................................................... 44 3.4.3 Defaults ............................................................................................................................................. 47 3.4.4 Rules .................................................................................................................................................. 48 3.5 BASE DE DADOS MERCADO ....................................................................................................................... 48 _________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 1

Bases de Dados II ISEP _________________________________________________________________________________________ 3.6 INTEGRIDADADE DA BD MERCADO ........................................................................................................... 50 3.7 INDEXES .................................................................................................................................................... 55 3.7.1 Clustered Indexes .............................................................................................................................. 57 3.7.2 Nonclustered Indexes......................................................................................................................... 57 3.7.3 Criao de indexes na BD Mercado .................................................................................................. 58 4. ACESSO A DADOS ..................................................................................................................................... 59 4.1 JOINS ......................................................................................................................................................... 60 4.2 FUNES DE AGREGAO ......................................................................................................................... 62 4.3 SUBQUERIES.............................................................................................................................................. 63 4.4 METACARCTERES ...................................................................................................................................... 65 4.5 UNIONS...................................................................................................................................................... 67 5. TRANSAES E BLOQUEAMENTOS ................................................................................................... 68 5.1 EXPLICIT TRANSACTIONS .......................................................................................................................... 69 5.2 AUTOCOMMIT TRANSACTIONS .................................................................................................................. 69 5.3 IMPLICIT TRANSACTIONS ........................................................................................................................... 70 5.4 NESTED TRANSACTIONS ............................................................................................................................ 71 5.5 BLOQUEAMENTOS ..................................................................................................................................... 72 6. CURSORS ..................................................................................................................................................... 73 6.1 MANIPULAO .......................................................................................................................................... 77 7. VIEWS ........................................................................................................................................................... 80 8. STORED PROCEDURES ........................................................................................................................... 83 8.1 VANTAGENS .............................................................................................................................................. 83 8.2 SYNTAX ..................................................................................................................................................... 84 8.3 PARMETROS ............................................................................................................................................ 86 8.4 EXERCCIOS ............................................................................................................................................... 87 9. USER FUNCTIONS ..................................................................................................................................... 91 9.1 UTILIZAO .............................................................................................................................................. 91 9.2 SCALAR FUNCTIONS .................................................................................................................................. 91 9.3 INLINE TABLE-VALUED FUNCTIONS .......................................................................................................... 92 9.4 MULTI-STATEMENT TABLE-VALUED FUNCTIONS ...................................................................................... 92 9.5 SYNTAX ..................................................................................................................................................... 93 9.6 EXERCICIOS ............................................................................................................................................... 96 10.EXERCCIOS .............................................................................................................................................. 97 11. TRIGGERS ............................................................................................................................................... 104 11.1 UTILIZAO .......................................................................................................................................... 104 11.1 SYNTAX ................................................................................................................................................. 105 11.2 EXERCCIOS ........................................................................................................................................... 108 13. EXERCCIOS GERAIS........................................................................................................................... 111 BIBLIOGRAFIA ............................................................................................................................................... 116

_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 2

Bases de Dados II ISEP _________________________________________________________________________________________

1 Introduo
1.1 Segurana
O SQLServer tem uma arquitectura Client/Server, pelo que, para ligar um cliente a um servidor SQL Server, no mnimo necessrio saber: O protocolo de rede que o servidor suporta Qual o tipo de autenticao O nome de rede ou o endereo IP do servidor O login e password 1.1.1 Tipos de Autenticao O SQLServer suporta dois mtodos de autenticao de utilizadores: SQL Server Authentication Este tipo de autenticao pressupe a existncia de um loginID e respectiva password para validar o acesso. Windows NT Authentication Usando este tipo de autenticao, no necessrio especificar o loginID nem a password porque a autenticao efectuada atravs da conta que o cliente usou para se validar no sistema operativo. Os atributos de segurana na rede permitem ou no o acesso ao SQLServer. 1.1.2 Roles Os Roles permitem a simplificao de processos de manuteno e atribuio de permisses de acesso a bases de dados. Podemos assignar Users a Roles e definir regras para os Roles. Desta forma, todos os Users com um determinado Role so validados da mesma forma. 1.1.3 Logins Logins so contas de utilizadores do SQLServer. Os Logins no so dependentes das bases de dados, no entanto, podem ser utilizadores das mesmas.

_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 3

Bases de Dados II ISEP _________________________________________________________________________________________

1.1.4 Users Um User um Login com permisso de acesso a uma determinada base de dados.

1.2 Acesso ao SQL Server


Os utilizadores no acedem directamente ao SQL Server, isto , tm que usar aplicaes escritas para esse fim, como por exemplo o ISQL. Essas aplicaes acedem ao SQL Server atravs de uma Database API (Database Application Programming Interface) 1.2.1 Database API Contm duas partes: Comandos (TRANSACT-SQL) passados para a base de dados. Conjunto de funes ou interfaces e mtodos que servem para enviar os comandos para a base de dados e processar os resultados retornados por ela. Transact-SQL a linguagem usada no SQL Server Suporta todos os comandos SQL-92 Suporta extenses ODBC ao SQL-92 Suporta outras extenses especficas ao Transact-SQL

1.3 Servios SQLServer (Windows NT)


O SQLServer composto por um conjunto de servios (programas) que tm que estar a correr no servidor. 1.3.1 MSSQLServer Faz a gesto de todos os ficheiros que compem as bases de dados no servidor, e processa todos os comandos Transact-SQL enviados pelos clientes.

_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 4

Bases de Dados II ISEP _________________________________________________________________________________________

1.3.2 SQLServerAgent Permite gerir o escalonamento de actividades peridicas e notificar os administradores de problemas que ocorram no SQL Server. Componentes do servio: Jobs So objectos que consistem em um ou mais comandos a serem executados, em suma, so blocos de instrues Transact-SQL que podem ser escalonados, por exemplo, para serem executados a datas especficas ou segundo intervalos de tempo predefinidos. Alerts So aces a serem tomadas quando situaes de erro especficas (eventos) acontecerem. Os eventos podem ser, um determinado erro, um erro com uma severidade especfica, ou uma base de dados em vias de atingir o limite de espao predefinido. Pode ser configurado para executar aces tais como enviar um email, ou executar um Job que permita resolver a situao. Operators So pessoas identificadas pela sua conta de rede ou email, e que esto habilitadas para dar resposta aos erros que aconteam no SQLServer. Podem ser alvo de Alerts via email, pager ou comandos net send.

1.3.3 MSDTC (Distributed Transaction Coordinator) O MSDTC um gestor de transaces que permite s aplicaes cliente a incluso de diferentes fontes de dados numa nica transaco. Coordena a confirmao (commit) da transaco distribuida atravs de todos os servers envolvidos na transaco, de tal forma que todas as alteraes em todos os servers so todas confirmadas ou ento todas eliminadas.

_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 5

Bases de Dados II ISEP _________________________________________________________________________________________

1.4 Arquitectura da base de dados no SQL Server


Componentes lgicos Componentes fsicos 1.4.1 Arquitectura lgica Datatypes Tables Indexes Views Constraints Rules Defaults Stored procedures Triggers User data types 1.4.2 Arquitectura fsica Page a unidade fundamental de espao para o registo da informao no SQL Server. Cada pgina tem 8K, o que significa que no SQL Server as bases de dados tm 128 pages por megabyte. Tipos de pgina (Data, Index, Text & Image, Global Allocation Map, Page Free Space, Index Allocation Map) Header - Informao de controlo - Espao livre - ObjectID do objecto a quem a pgina pertence Data rows - Cada linha no pode ocupar mais do que uma pgina, e por isso, no SQL Server o tamanho maximo de uma linha de 8060 bytes Offset - Tem um registo por cada linha que existe na pgina 96 bytes

8096 bytes

36 bytes

_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 6

Bases de Dados II ISEP _________________________________________________________________________________________

Data Page
Header Linha 1 Linha 2 ... ...

...

123

96

As linhas das tabelas so guardadas em Data Pages. Cada linha no pode ocupar mais do que uma pgina, pelo que o tamanho maximo de uma linha 8060 bytes. Header Informao de controlo. Alguns campos so usados pelo SQLServer para verificao de consistncia nas estruturas de dados e outros para navegao nas pginas. Page ID (FileID + Page#) Apontadores para a anterior e a proxima pginas Tipo de pgina Index ID 0 Heap table 1 Clustered table >1 Nonclustered index 255 Text ou Image table

Offset Define a localizao de uma linha numa pgina (rowid). As linhas so inseridas na rea livre no fim de uma pgina. Insero e eliminao de linhas numa data page. Exemplo para uma tabela com um campo de 20 bytes e n linhas por pgina.
_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 7

Bases de Dados II ISEP _________________________________________________________________________________________ Header Linha 0: Bases de Dados I Linha 1: Engenharia Software ... Linha n-1: Anlise de Sistemas 96+linha*rowlength ... Header Linha 0: Bases de Dados I Engenharia Software 116 96

... Linha n-1: Anlise de Sistemas 96+linha*rowlength Eliminao de Engenharia de Software ... Header Linha 0: Bases de Dados I Engenharia Software 0 96

... Linha n-1: Anlise de Sistemas Linha n: Bases de Dados II 96+linha*rowlength Insero de Bases de Dados II

... Header

96

Linha 0: Bases de Dados I ... Linha n-2: Anlise de Sistemas Linha n-1: Bases de Dados II Linha n: Projecto 96+linha*rowlength Insero de Projecto

...

116

96

Index Page Uma Index Page tem a mesma estrutura que uma Data Page excepo do tipo de informao guardada. Geralmente, uma linha numa Index Page tem a chave do ndice e um apontador para a pgina no nvel seguinte. Clustered Indexes, nonleaf pages Cada linha contm a chave do ndice e um apontador (fileID e pageAddress) para a proxima pgina na rvore.
_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 8

Bases de Dados II ISEP _________________________________________________________________________________________

O Leaf Level de um Clustered Index contm os dados, logo, tem exactamente a mesma estrutura de uma Data Page. Nonclustered Indexes, nonleaf pages Cada linha contm a chave do ndice e um apontador (fileID e pageAddress) para a proxima pgina na rvore. Adicionalmente contm uma referncia (RowId) para a Data Row a que a linha do ndice se refere. o Nonclustered Tables: RowID = (File ID, Page Address, Offset Address) o Clustered Tables: Clustered Key Nonclustered Indexes, leaf pages RowID ou Clustered Key, conforme a tabela ou no clustered. Text & Image Page Texto e imagens so datatypes associados a objectos que pressupem grande volume de informao. Cada coluna deste tipo suporta at 2Gb de dados. Texto e imagens no so guardados conjuntamente com os dados da linha associada, mas sim em pginas prprias. Para cada valor destas colunas, o que guardado na Data Page um apontador (16 byte) para a localizao da Text & Image Page. Global Allocation Map Page As Global Allocation Map Pages (GAM) permitem ao SQLServer o controlo do espao alocado, ou seja, permite saber quais os Extents que esto alocados para objectos e que tipo de Extent se trata (Mixed ou Uniform). Global Allocation Map Regista os Extents alocados, independentemente de serem ou no uniformes. Cada bit na pgina, excepo do Header, representa um Extent, onde 1 significa que no est alocado e 0 que est.
_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 9

Bases de Dados II ISEP _________________________________________________________________________________________

Cada pgina representa 64768 extents (8096 * 8), ou seja 4Gb (8096 * 8 * 64Kb) de dados Shared Global Allocation Map A diferena relativamente ao Global Allocatiom Map que este controla a alocao do espao livre em Mixed Extents. Cada bit na pgina, excepo do Header, representa um Extent, onde 1 significa que um Mixed Extent e tem espao livre (pelo menos uma pgina) e 0 que a pgina no est alocada, que um Uniform Extent, ou ento que um Mixed Extent sem pginas livres. Extent GAM bit Livre 1 Uniforme 0 Mixed, sem pginas livres 0 Mixed, com pginas livres 0 SGAM bit 0 0 0 1

Quando o SQLServer necessita de alocar um Uniform Extent, procura na GAM um bit com 1 (livre) e altera para 0. Para encontrar um Mixed Extent com pginas livres, procura na GAM um bit com 1, altera-o para 0 e em seguida altera o bit correspondente na SGAM para 1. Index Allocation Map Page As Index Allocation Map Pages (IAM) permitem ao SQLServer o controlo do espao alocado por ndices. A estrutura das IAM semelhante s GAM, ou seja um bitmap onde cada bit representa o uso dos Extents. Page Free Space Page As PFS registam se as pginas esto alocadas e qual a quantidade de espao livre. Cada PFS cobre 8000 pginas e cada pgina um bitmap que indica se a pgina est live, se est de 1 a 50%, 51 a 80%, 81 a 95%, ou mais de 95% ocupada. A PFS a primeira pgina de cada ficheiro.

_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 10

Bases de Dados II ISEP _________________________________________________________________________________________

Extent Se o SQLServer alocasse pginas uma de cada vez quando necessrio, haveria grande fragmentao dos dados das tabelas ou ndices. Uma consequncia desse facto que a pesquisa nestas tabelas seria ineficiente, e por isso, as pginas associadas a um determinado objecto (tabela ou ndice) so agrupadas em Extents. a unidade fundamental de espao para a alocao de tabelas e ndices. Cada extent so 8 pginas contguas, ou seja, 64Kb. Uniform Extent Pertence a um nico objecto. Todas as 8 pginas pertencem a esse objecto. Mixed Extent Pode ser partilhado por oito objectos, um por cada pgina. Quando uma tabela ou ndice so criados, o SQLServer aloca uma pgina num Mixed Extent e medida que a tabela ou ndice vai crescendo vai reservando Uniform Extents.

1.4 Bases de dados do sistema


A base de dados dos sistema um conjunto de ficheiros que so criados na mesma altura da criao da BD ou medida que esta vai crescendo. Para o SQLServer, o nmero mnimo de ficheiros de uma BD dois pela razo que o Transaction Log sempre separado dos ficheiros de dados. O tamanho maximo de um Data File 32Tb e de um Log File 4Tb. 1.4.1 Master Guarda toda a informao do sistema SQLServer Configurao do sistema Contas dos utilizadores Existncia de outras bases de dados
_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 11

Bases de Dados II ISEP _________________________________________________________________________________________

Localizao das primary files que contm a informao de inicializao das bases de dados System Tables System Stored Procedures Mensagens de erro ... A Master crtica para o sistema SQLServer. uma base de dados que tende a ter pouca actividade e normalmente pequena. As alteraes efectuadas na Master so sempre resultado da insero ou modificao de registos nas tabelas do sistema, e essas alteraes resultam de: Criao, alterao ou eliminao de bases de dados Criao ou eliminao de Logins e Users Criao ou eliminao de Backup Devices Reconfigurao do SQLServer 1.4.2 Model A Model um template para todas as bases de dados. Quando se cria uma base de dados, o contedo da model copiado, e o restante espao preenchido com pginas vazias. Se quisermos que determinados objectos sejam criados automaticamente quando se cria uma base de dados, podemos alterar a Model por forma a optimizar o processo. Os objectos que podem ser adicionados so Tables, Rules, Defaults, User-Defined Datatypes, Users, etc. 1.4.3 Tempdb A TempDB guarda todas as tabelas e stored procedures temporrios. um recurso global, isto , todos os utilizadores de todas as bases de dados guardam a sua informao temporria na tempdb. recriada de cada vez que o SQL Server iniciado. Como todas as tabelas e stored procedures temporrios so apagados quando o utilizador desliga a sesso, nunca fica nenhuma informao importante na TempDB, de uma sesso para outra. Preenche outro tipo de necessidades de espao temporrias.

_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 12

Bases de Dados II ISEP _________________________________________________________________________________________

1.4.4 Msdb
A MsDB usada pelo servio SQLServerAgent para gerir o escalonamento dos Alerts, Jobs, e registo dos Operators. Alm do SQLServerAgent, o SQLServer usa a MsDB para guardar informao sobre backups.

1.5 Tabelas do sistema


O SQLServer guarda toda a informao respeitante a configurao, segurana e objectos nas tabelas do sistema. Algumas dessas tabelas so na verdade Views mas esto documentadas como tabelas. Para cada base de dados, o conjunto de todas as tabelas que a descrevem chamado o Database Catalog. H ainda um conjunto de tabelas que descrevem a configurao do SQLServer, so o System Catalog. O Dicionrio de Dados representa dados sobre os dados (metadados) e podemos considerar que o conjunto de todas as tabelas que representam informao sobre tabelas e todos os restantes objectos no SQLServer.

1.6 Database Files


1.6.1 Data files Primary datafiles (*.mdf) Todas as bases de dados tm uma primary datafile. A primary datafile o incio da base de dados e aponta para o resto dos ficheiros da mesma. Secondary datafile (*.ndf) Algumas bases de dados podem no ter secondary datafiles enquanto outras podem ter vrias. Log files (*.ldf) Guarda toda a informao necessria para recuperar uma base de dados. Existe pelo menos um log file por base de dados. Cada data file tem um ID number que o identifica unvocamente, e contm um determinado nmero de pginas, sendo estas numeradas sequencialmente. Para identificar uma pgina na base de dados, necessrio saber o file ID e o nmero da pgina.
_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 13

Bases de Dados II ISEP _________________________________________________________________________________________

1.6.2 Nomes de ficheiros no SQL Server logical_file_name o nome usado para referir o ficheiro em comandos Transact SQL os_file_name o nome fsico do ficheiro. File groups o Os data files podem ser agrupados em filegroups para fins administrativos. o Nenhum data file pode pertencer a mais do que um file group. o Log files nunca podem pertencer a um file group. o Primary file group o Contm o primary data file e qualquer outro ficheiro que no seja incluido em nenhum file group. o User defined file group o Qualquer file group especificado usando a keyword FILEGROUP nos comandos CREATE DATABASE ou ALTER DATABASE. o Default file group o Contm pginas para todas as tabelas e ndices que no tm file group especificado na altura em que so criadas. o Se nenhum default filegroup for especificado, o default file group torna-se o primary file group.

_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 14

Bases de Dados II ISEP _________________________________________________________________________________________

2. Introduo ao Transact-SQL
O Transact-SQL uma linguagem que tem como estrutura base o standard ANSI SQL-92 ISO e que permite comunicar com o SQL Server. A Microsoft adicionou vrias funcionalidades no standard na norma SQL92.

2.1 DCL Data Control Language


A DCL contm instrues que permitem alterar as permisses de acesso do utilizador a manipulao de dados : Grant D permisso ao utilizador para manipular dados e/ou instrues SQL. Ex. Utilizar a base de dados Northwind e executar o seguinte comando: GRANT INSERT ON customers TO public Deny Nega a permisso ao utilizador, mesmo que esta tenha sido dada num contexto de herana. Ex. DENY INSERT ON customers TO public Revoke Retira permisses feitas, Grant ou Deny. Ex. REVOKE INSERT ON customers TO public 2.1.1 Syntax da instruo Grant GRANT {ALL [PRIVILEGES] | permission[,...n]} { [(column[,...n])] ON {table | view} | ON {table | view}[(column[,...n])] | ON {stored_procedure | extended_procedure} } TO security_account[,...n] [WITH GRANT OPTION] [AS {group | role}] Arguments
ALL Specifies that all applicable permissions are being granted. For statement permissions, ALL can be used only by members of the sysadmin role. For object permissions, ALL can be used by members of the sysadmin and db_owner roles, and database object owners.

statement
_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 15

Bases de Dados II ISEP _________________________________________________________________________________________

Is the statement for which permission is being granted. The statement list can include: CREATE DATABASE CREATE DEFAULT CREATE PROCEDURE CREATE RULE CREATE TABLE CREATE VIEW BACKUP DATABASE BACKUP LOG n A placeholder indicating that the item can be repeated in a comma-separated list. TO Specifies the security account list. security_account Is the security account to which the permissions are applied. The security account can be a: Microsoft SQL Server user. SQL Server role. Microsoft Windows NT user. Windows NT group. When a permission is granted to a SQL Server user or Windows NT user account, the specified security_account is the only account affected by the permission. If a permission is granted to a SQL Server role or a Windows NT group, the permission affects all users in the current database who are members of the group or role. If there are permission conflicts between a group or role and its members, the most restrictive permission (DENY) takes precedence. security_account must exist in the current database; permissions cannot be granted to a user, role, or group in another database, unless the user has already been created or given access to the current database. Two special security accounts can be used with GRANT. Permissions granted to the public role are applied to all users in the database. Permissions granted to the guest user are used by all users who do not have a user account in the database.

PRIVILEGES Is an optional keyword that can be included for SQL-92 compliance. permission Is an object permission that is being granted. When permissions are granted on a table or a view, the permission list can include one or more of these statements: SELECT, INSERT, DELETE, or UPDATE. Object permissions granted on a table can also include REFERENCES, and object permissions granted on a procedure can include EXECUTE. When permissions are granted on columns, the permissions list can include SELECT or UPDATE. When permissions are granted on stored procedures, the permissions list can include only EXECUTE.
_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 16

Bases de Dados II ISEP _________________________________________________________________________________________

When a user adds a row to a table with a FOREIGN KEY constraint, or changes data in a column with a FOREIGN KEY constraint, SQL Server must validate the data in the column with the data referenced in the FOREIGN KEY constraint. If the user does not have SELECT permissions on the referenced column or table, the REFERENCES permission for the column must be granted to the user. The REFERENCES permission cannot be granted for a system table. column Is the name of a column in the current database for which permissions are being granted. table Is the name of the table in the current database for which permissions are being granted. view Is the name of the view in the current database for which permissions are being granted. stored_procedure Is the name of the stored procedure in the current database for which permissions are being granted. extended_procedure Is the name of the extended stored procedure for which permissions are being granted. WITH GRANT OPTION Specifies that the security_account is given the ability to grant the specified object permission to the other security accounts. The WITH GRANT OPTION clause is valid only with object permissions. AS {group | role} Specifies the optional name of the security account in the current database that has the authority to execute the GRANT statement. AS is used when permissions on an object are granted to a group or role, and the object permissions need to be further granted to users who are not members of the group or role. Because only a user, rather than a group or role, can execute a GRANT statement, a specific member of the group or role grants permissions on the object under the authority of the group or role.

2.1.2 Syntax da instruo Deny DENY {ALL [PRIVILEGES] | permission[,...n]} { [(column[,...n])] ON {table | view} | ON {table | view}[(column[,...n])] | ON {stored_procedure | extended_procedure}} TO security_account[,...n] [CASCADE]

_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 17

Bases de Dados II ISEP _________________________________________________________________________________________

Arguments
So semelhantes aos descritos atrs para a instruo Grant, com a excepo de : CASCADE Specifies that permissions are being denied from security_account as well as any other security accounts granted permissions by security_account. Use CASCADE when denying a grantable permission. If CASCADE is not specified and the specified user is granted WITH GRANT OPTION permission, an error is returned.

2.1.3 Syntax da instruo Revoke REVOKE [GRANT OPTION FOR] {ALL [PRIVILEGES] | permission[,...n]} { [(column[,...n])] ON {table | view} | ON {table | view}[(column[,...n])] | {stored_procedure | extended_procedure} } {TO | FROM} security_account[,...n] [CASCADE] [AS {group | role}] Arguments
So semelhantes aos descritos atrs para a instruo Deny, com a excepo de : GRANT OPTION FOR Specifies that WITH GRANT OPTION permissions are being removed. Use the GRANT OPTION FOR keywords with REVOKE to remove the effects of the WITH GRANT OPTION setting specified in the GRANT statement. The user still has the permissions, but cannot grant the permissions to other users. If the permissions being revoked were not originally granted using the WITH GRANT OPTION setting, GRANT OPTION FOR is ignored if specified, and permissions are revoked as usual. If the permissions being revoked were originally granted using the WITH GRANT OPTION setting, specify both the CASCADE and GRANT OPTION FOR clauses; otherwise, an error is returned.

_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 18

Bases de Dados II ISEP _________________________________________________________________________________________

2.2 DDL Data Definition Language


A DDL contm instrues que permitem criar, alterar e apagar tabelas e bases de dados. Create Permite criar Alter Permite alterar Drop Permite apagar Ex. CREATE TABLE aluno (NAluno int, Nome Varchar(40)) DROP TABLE aluno

2.3 DML Data Manipulation Language


A DML contm instrues que permitem manipular os dados da BD, como por exemplo : Select Permite seleccionar dados Insert Permite inserir dados Update Permite alterar dados Delete Permite apagar dados Ex. SELECT * FROM customers

2.4 Variveis, operadores, funes e instrues de controlo


Existem instrues adicionais que facilitam toda a gesto de dados, tais como variveis, operadores, funes, etc. 2.4.1 Variveis 2.4.1.1 Variveis locais Uma varivel no T-SQL um objecto que consegue guardar um determinado valor durante um processamento. Depois da varivel ser declarada, uma instruo T-SQL pode atribuir-lhe um valor. Mais tarde uma outra instruo pode ir buscar o seu valor.

_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 19

Bases de Dados II ISEP _________________________________________________________________________________________

Ex. DECLARE @Cidade Varchar(40) SET @Cidade = 'London' SELECT * FROM customers WHERE City = @Cidade

2.4.1.2 Variveis globais So variveis previamente declaradas pelo sistema, que se distinguem das locais por terem no incio os smbolos @@. Ex. SELECT @@VERSION
@@CONNECTIONS (T-SQL)

Returns the number of connections or attempted connections since Microsoft SQL Server was last started.
@@CPU_BUSY (T-SQL) Returns the time in milliseconds (based on the resolution of the system timer) that the CPU has spent doing work since Microsoft SQL Server was last started. @@CURSOR_ROWS (T-SQL) Returns the number of qualifying rows that are currently in the last cursor opened on the connection. To improve performance, Microsoft SQL Server can populate large keyset and static cursors asynchronously. @@CURSOR_ROWS can be called to determine the number of the rows that qualify for a cursor have been retrieved at the time @@CURSOR_ROWS is called. Return Description value The cursor is being populated asynchronously. The value returned (-m) is the -m number of rows currently in the keyset. The cursor is dynamic. Because dynamic cursors reflect all changes, the number -1 of rows that qualify for the cursor is constantly changing. It can never be definitely stated that all qualified rows have been retrieved. No cursors have been opened, no rows qualified for the last opened cursor, or 0 the last-opened cursor is closed or deallocated. The cursor is fully populated. The value returned (n) is the total number of rows n in the cursor.

_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 20

Bases de Dados II ISEP _________________________________________________________________________________________

@@DATEFIRST (T-SQL) Returns the current value of the SET DATEFIRST parameter, which indicates the specified first day of each week: 1 for Monday, 2 for Wednesday, and so on through 7 for Sunday. @@DBTS (T-SQL) Returns the value of the current timestamp data type for the current database. This timestamp is guaranteed to be unique in the database. @@ERROR (T-SQL) Returns the error number for the last Transact-SQL statement executed. @@FETCH_STATUS (T-SQL) Returns the status of the last cursor FETCH statement issued against any cursor currently opened by the connection. Return Description value 0 FETCH statement was successful. FETCH statement failed or the row was beyond the result -1 set. -2 Row fetched is missing. @@IDENTITY (T-SQL) Returns the last-inserted identity value. @@IDLE (T-SQL) Returns the time in milliseconds (based on the resolution of the system timer) that Microsoft SQL Server has been idle since it was last started. @@IO_BUSY (T-SQL) Returns the time in milliseconds (based on the resolution of the system timer) that Microsoft SQL Server has spent doing input and output operations since it was last started. @@LANGID (T-SQL) Returns the local language ID of the language currently in use. @@LANGUAGE (T-SQL) Returns the name of the language currently in use. @@LOCK_TIMEOUT (T-SQL) Returns the current lock time-out setting, in milliseconds, for the current session. @@MAX_CONNECTIONS (T-SQL) Returns the maximum number of simultaneous user connections allowed on a Microsoft SQL Server. The number returned is not necessarily the number that is currently configured. @@MAX_PRECISION (T-SQL) Returns the level of precision used by decimal and numeric data types as currently set in the server.
_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 21

Bases de Dados II ISEP _________________________________________________________________________________________

@@NESTLEVEL (T-SQL) Returns the nesting level of the current stored procedure execution (initially 0). @@OPTIONS (T-SQL) Returns information about current SET options. @@PACK_RECEIVED (T-SQL) Returns the number of input packets read from the network by Microsoft SQL Server since it was last started. @@PACK_SENT (T-SQL) Returns the number of output packets written to the network by Microsoft SQL Server since it was last started. @@PACKET_ERRORS (T-SQL) Returns the number of network packet errors that have occurred on Microsoft SQL Server connections since the last time SQL Server was started. @@PROCID (T-SQL) Returns the stored procedure ID of the current procedure @@REMSERVER (T-SQL) Returns the name of the remote Microsoft SQL Server database server as it appears in the login record. @@ROWCOUNT (T-SQL) Returns the number of rows affected by the last statement. @@SERVERNAME (T-SQL) Returns the name of the local server running Microsoft SQL Server. @@SERVICENAME (T-SQL) Returns the name of the registry key under which Microsoft SQL Server is running. @@SPID (T-SQL) Returns the server process ID of the current user process. @@TEXTSIZE (T-SQL) Returns the current value of the TEXTSIZE option of the SET statement, which specifies the maximum length, in bytes, of text or image data that a SELECT statement returns. @@TIMETICKS (T-SQL) Returns the number of microseconds per tick. @@TOTAL_ERRORS (T-SQL) Returns the number of disk read/write errors encountered by Microsoft SQL Server since it was last started.
_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 22

Bases de Dados II ISEP _________________________________________________________________________________________

@@TOTAL_READ (T-SQL) Returns the number of disk reads (not cache reads) by Microsoft SQL Server since it was last started. @@TOTAL_WRITE (T-SQL) Returns the number of disk writes by Microsoft SQL Server since it was last started. @@TRANCOUNT (T-SQL) Returns the number of active transactions for the current connection. @@VERSION (T-SQL) Returns the date, version, and processor type for the current installation of Microsoft SQL Server.

2.4.2 Operadores O SQL Server tem vrios tipos de operadores para manipulao de expresses. Os principais so : Aritmticos Comparao Lgicos Concatenao de strings

2.4.2.1 Operadores aritmticos Permitem efectuar clculos aritmticos sobre valores isolados ou campos da BD. Ex. SELECT ProductName, UnitPrice * UnitsInStock FROM Products
Operator + (Add) (Subtract) * (Multiply) / (Divide) % (Modulo) Meaning Addition. Subtraction. Multiplication. Division. Returns the integer remainder of a division. For example, 12 % 5 = 2 because the remainder of 12 divided by 5 is 2.

_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 23

Bases de Dados II ISEP _________________________________________________________________________________________

2.4.2.2 Operadores para comparaes Existem operadores que permitem comparar valores numricos, strings e datas. Ex. SELECT * FROM Employees WHERE employeeID > 5
Operator = (Equals) > (Greater Than) < (Less Than) >= (Greater Than or Equal To) <= (Less Than or Equal To) <> (Not Equal To) != (Not Equal To) !< (Not Less Than) !> (Not Greater Than) Meaning Equal to. Greater than. Less than. Greater than or equal to. Less than or equal to. Not equal to. Not equal to (not SQL-92 standard). Not less than (not SQL-92 standard).

2.4.2.3 Operadores lgicos Os operadores lgicos testam se uma condio ou no verdadeira. Ex. SELECT * FROM Employees WHERE employeeID BETWEEN 3 AND 5
Operator ALL AND ANY BETWEEN EXISTS IN LIKE NOT OR SOME Meaning TRUE if all of a set of comparisons are TRUE. TRUE if both Boolean expressions are TRUE. TRUE if any one of a set of comparisons are TRUE. TRUE if the operand is within a range. TRUE if a subquery contains any rows. TRUE if the operand is equal to one of a list of expressions. TRUE if the operand matches a pattern. Reverses the value of any other Boolean operator. TRUE if either Boolean expression is TRUE. TRUE if some of a set of comparisons are TRUE.

2.4.2.4 Operador para concatenao de strings (operador +) O operador + permite concatenar vrias strings numa nica. Ex. SELECT Firstname + ' ' + Lastname AS Nome FROM Employees
_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 24

Bases de Dados II ISEP _________________________________________________________________________________________

2.4.3 Funes O SQL Server tem vrios tipos de funes para manipulao de dados, os principais grupos so as de agregao, de data e hora, matemticas, de metadata, de segurana, de strings e as de sistema.

2.4.3.1 Funes de agregao Efectuam clculos num conjunto de valores e retornam um nico valor. Ex. SELECT AVG(UnitPrice) FROM products
Function SUM([ALL | DISTINCT] expression AVG([ALL | DISTINCT] expression COUNT([ALL | DISTINCT] expression COUNT(*) MAX(expression) MIN(expression) Meaning Total of the values in the numeric expression Average of the values in the numeric expression Number of values in the expression Number of selected rows Highest value in the expression Lowest value in the expression

2.4.3.2 Funes de data e hora Executam operaes em datas e horas e retornam uma string, um valor numrico, uma data ou horas. Ex. SELECT GETDATE()
DATEADD DATEDIFF DATENAME DATEPART DAY GETDATE MONTH YEAR

_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 25

Bases de Dados II ISEP _________________________________________________________________________________________

2.4.3.3 Funes matemticas Permitem efectuar clculos matemticos sobre valores ou campos da base de dados. Ex. SELECT PI()
ABS ACOS ASIN ATAN ATN2 CEILING COS COT DEGREES EXP FLOOR LOG LOG10 PI POWER RADIANS RAND ROUND SIGN SIN SQUARE SQRT TAN

2.4.3.4 Funes de metadata Retornam informao acerca da base de dados e dos seus objectos. Ex. SELECT COL_LENGTH('categories', 'categoryname')
COL_LENGTH COL_NAME COLUMNPROPERTY DATABASEPROPERTY DB_ID DB_NAME FILE_ID FILE_NAME FILEGROUP_ID FILEGROUP_NAME FILEGROUPPROPERTY FILEPROPERTY FULLTEXTCATALOGPROPERTY FULLTEXTSERVICEPROPERTY INDEX_COL INDEXPROPERTY OBJECT_ID OBJECT_NAME OBJECTPROPERTY @@PROCID TYPEPROPERTY

_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 26

Bases de Dados II ISEP _________________________________________________________________________________________

2.4.3.5 Funes de segurana Retornam informaes acerca de utilizadores ou grupos de utilizadores. Ex. SELECT SUSER_NAME()
IS_MEMBER IS_SRVROLEMEMBER SUSER_ID SUSER_NAME SUSER_SID SUSER_SNAME USER_ID USER

2.4.3.6 Funes de strings Efectuam operaes em strings e retornam uma string ou um valor numrico. Ex. SELECT FirstName, Len(FirstName) FROM Employees
ASCII CHAR CHARINDEX DIFFERENCE LEFT LEN LOWER LTRIM NCHAR PATINDEX REPLACE QUOTENAME REPLICATE REVERSE RIGHT RTRIM SOUNDEX SPACE STR STUFF SUBSTRING UNICODE UPPER

2.4.3.7 Funes de sistema Retornam valores que esto relacionados com valores, ou objectos do sistema. Ex. SELECT SYSTEM_USER

_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 27

Bases de Dados II ISEP _________________________________________________________________________________________

APP_NAME CASE CAST and CONVERT COALESCE CURRENT_TIMESTAMP CURRENT_USER DATALENGTH @@ERROR FORMATMESSAGE GETANSINULL HOST_ID HOST_NAME IDENT_INCR IDENT_SEED @@IDENTITY

IDENTITY (Function) ISDATE ISNULL ISNUMERIC NEWID NULLIF PARSENAME PERMISSIONS @@ROWCOUNT SESSION_USER STATS_DATE SYSTEM_USER @@TRANCOUNT USER_NAME

2.4.4 Elementos de controlo Permitem controlar o fluxo dos dados na execuo de instrues T-SQL. Ex. IF (SELECT UnitsInStock FROM products WHERE ProductID = 1) <= 0 PRINT 'No existe stock' ELSE PRINT 'Existe stock'
Defines a statement block. Exits the innermost WHILE loop. Restarts a WHILE loop. Continues processing at the statement following the label as defined by GOTO label label. Defines conditional, and optionally, alternate execution when a condition IF...ELSE is FALSE. RETURN Exits unconditionally. WAITFOR Sets a delay for statement execution. WHILE Repeats statements while a specific condition is TRUE. Other Transact-SQL statements that can be used with control-of-flow language statements are: /*...*/ (Comment) EXECUTE -- (Comment) PRINT CASE RAISERROR DECLARE @local_variable
_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 28

Keyword BEGIN...END BREAK CONTINUE

Description

Bases de Dados II ISEP _________________________________________________________________________________________

2.5 Modos de execuo do T-SQL


Existem vrias opes para executar instrues T-SQL que variam conforme a necessidade do utilizador : dinamicamente, em batch, em script e utilizando transaes.

2.5.1 T-SQL Dinmico possvel construir instrues SQL em run-time e executa-las atravs da instruo EXEC[UTE]. Ex. DECLARE @SQLString NVARCHAR(500) DECLARE @Tabela NVARCHAR(50) SET @Tabela = 'products' SET @SQLString = 'select * from ' + @tabela EXEC (@SQLString)

2.5.2 Batch Um batch um conjunto de uma ou mais instrues SQL que so enviadas como uma s para serem processadas. Cada batch compilado e optimizado num nico plano de execuo. No entanto no momento da execuo o compilador no detecta possveis alteraes a colunas, ou seja, no mesmo batch no pode existir uma linha a alterar o nome de uma coluna e na linha seguinte uma instruo de seleco com o novo nome da coluna. Se num conjunto de instrues acontecer um erro, ento as instrues seguintes no sero executadas. Ex. SELECT * FROM products WHERE ProductID = 3 SELECT * FROM products WHERE ProductID > 3

_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 29

Bases de Dados II ISEP _________________________________________________________________________________________

2.5.3 Scripts Um script um conjunto de batches que podem ser guardados num ficheiro em disco e que podem ser executados no Query Analyzer, no OSQL ou outro utilitrio SQL. O fim de cada batch assinalado pela instruo GO, o que implica que todas as instrues de um batch no tenham nenhuma relao com o batch seguinte (ex. variveis). So muito utilizados para guardas a estrutura de dados da BD. Ex. DECLARE @SQLString NVARCHAR(500) SET @SQLString = 'select * from categories' EXEC (@SQLString) GO EXEC (@SQLString Nota : D um erro no segundo script, pois a varivel no existe.

2.5.4 Transaes Uma transao interpretada como um nico comando (apesar de poderem ser vrias instrues SQL), ou seja, ou executado completamente ou no, no existe o meio termo. Se acontecer um erro aps a execuo de algumas instrues, essas instrues so desfeitas. A transao iniciada com a instruo BEGIN TRANSACTION e terminada com COMMIT TRANSACTION quando tudo correu bem, ou com ROLLBACK TRANSACTION quando algo corre mal. Ex. BEGIN TRANSACTION UPDATE products SET ProductName = 'Novo Nome' WHERE ProductID = 1; UPDATE products SET ProductName = NULL WHERE ProductID = 2 IF (@@Error >0) ROLLBACK TRANSACTION ELSE COMMIT TRANSACTION
_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 30

Bases de Dados II ISEP _________________________________________________________________________________________

3. Criao da BD
3.1 Introduo
Uma base de dados no SQL Server consiste num conjunto de tabelas que permitem guardar dados numa forma estruturada, e outros objectos (views, indexes, stored procedures, triggers, etc.) que permitem facilitar toda as actividades da base de dados, tais como guardar informao, aceder a informao, alterar dados, etc.

3.2 Criar, alterar e apagar uma BD


Ex. CREATE DATABASE Gestao ON ( NAME = GestaoDat, FILENAME = 'c:\Projecto\BD\GestaoDat.mdf', SIZE = 10, MAXSIZE = 30, FILEGROWTH = 5 ) LOG ON ( NAME = 'GestaoLog', FILENAME = 'c:\Projecto\BD\GestaoLog.ldf', SIZE = 5MB, MAXSIZE = 15MB, FILEGROWTH = 5MB )
_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 31

Bases de Dados II ISEP _________________________________________________________________________________________

Ex. ALTER DATABASE Gestao MODIFY FILE (NAME = Gestaodat, SIZE = 10MB) Ex. DROP DATABASE Gestao

Syntax CREATE DATABASE database_name [ ON [PRIMARY] [ <filespec> [,...n] ] [, <filegroup> [,...n] ] ] [ LOG ON { <filespec> [,...n]} ] [ FOR LOAD | FOR ATTACH ] <filespec> ::= ( [ NAME = logical_file_name, ] FILENAME = 'os_file_name' [, SIZE = size] [, MAXSIZE = { max_size | UNLIMITED } ] [, FILEGROWTH = growth_increment] ) [,...n] <filegroup> ::= FILEGROUP filegroup_name <filespec> [,...n] Arguments
database_name Is the name of the new database. Database names must be unique within a server and conform to the rules for identifiers. database_name can be up to 128 characters, unless no logical name is specified for the log. If no logical log file name is specified, Microsoft SQL Server generates a logical name by appending a suffix to database_name. This limits database_name to 123 characters so that the generated logical log file name is less than 128 characters. ON Specifies that the disk files used to store the data portions of the database (data files) are defined explicitly. The keyword is followed by a comma-delimited list of <filespec> items defining the data files for the primary filegroup. The list of files in the primary filegroup can be followed by an optional, comma-delimited list of <filegroup> items defining user filegroups and their files.
_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 32

Bases de Dados II ISEP _________________________________________________________________________________________

PRIMARY Specifies that the associated <filespec> list defines the primary file. The primary filegroup contains all of the database system tables. It also contains all objects not assigned to user filegroups. The first <filespec> entry in the primary filegroup becomes the primary file, which is the file containing the logical start of the database and its system tables. A database can have only one primary file. If PRIMARY is not specified, the first file listed in the CREATE DATABASE statement becomes the primary file. n Is a placeholder indicating that multiple files can be specified for the new database. LOG ON Specifies that the disk files used to store the database log (log files) are explicitly defined. The keyword is followed by a comma-delimited list of <filespec> items defining the log files. If LOG ON is not specified, a single log file is automatically created with a system-generated name and a size that is 25 percent of the sum of the sizes of all the data files for the database. FOR LOAD This clause is supported for compatibility with earlier versions of Microsoft SQL Server. The database is created with the dbo use only database option turned on, and the status is set to loading. This is not needed in SQL Server version 7.0 because the RESTORE statement can re-create a database as part of the restore operation. If you attach a database to a server other than the server from which the database was detached, and the detached database was enabled for replication, you should run sp_removedbreplication to remove replication from the database. FOR ATTACH Specifies that a database is attached from an existing set of operating system files. There must be a <filespec> entry specifying the first primary file. The only other <filespec> entries needed are those for any files that have a different path from when the database was first created or last attached. A <filespec> entry must be specified for these files. The database being attached must have been created using the same code page and sort order as SQL Server. Use the sp_attach_db system stored procedure instead of using CREATE DATABASE FOR ATTACH directly. Use CREATE DATABASE FOR ATTACH only when you must specify more than 16 <filespec> items. NAME Specifies the logical name for the file defined by the <filespec>. The NAME parameter is not required when FOR ATTACH is specified. logical_file_name Is the name used to reference the file in any Transact-SQL statements executed after the database is created. logical_file_name must be unique in the database and conform to the rules for identifiers. The name can be a character or Unicode constant, or a regular or delimited identifier. FILENAME Specifies the operating-system file name for the file defined by the <filespec>. 'os_file_name' Is the path and file name used by the operating system when it creates the physical file defined by the <filespec>. The path in os_file_name must specify a directory on the
_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 33

Bases de Dados II ISEP _________________________________________________________________________________________

server in which SQL Server is installed. os_file_name cannot specify a directory in a compressed file system. If the file is being created on a raw partition, os_file_name must specify only the drive letter of an existing raw partition. Only one file can be created on each raw partition. Files on raw partitions do not autogrow; therefore, the MAXSIZE and FILEGROWTH parameters are not needed when os_file_name specifies a raw partition. SIZE Specifies the size of the file defined in the <filespec>. When a SIZE parameter is not supplied in the <filespec> for a primary file, SQL Server uses the size of the primary file in the model database. When a SIZE parameter is not specified in the <filespec> for a secondary or log file, SQL Server makes the file 1 MB. size Is the initial size of the file defined in the <filespec>. The KB and MB suffixes can be used to specify kilobytes or megabytes, the default is MB. Specify a whole number; do not include a decimal. The minimum value for size is 512 KB. If size is not specified, the default is 1 MB. The size specified for the primary file must be at least as large as the primary file of the model database. MAXSIZE Specifies the maximum size to which the file defined in the <filespec> can grow. max_size Is the maximum size to which the file defined in the <filespec> can grow. The KB and MB suffixes can be used to specify kilobytes or megabytes, the default is MB. Specify a whole number; do not include a decimal. If max_size is not specified, the file grows until the disk is full. UNLIMITED Specifies that the file defined in the <filespec> grows until the disk is full. FILEGROWTH Specifies the growth increment of the file defined in the <filespec>. The FILEGROWTH setting for a file cannot exceed the MAXSIZE setting. growth_increment Is the amount of space added to the file each time new space is needed. Specify a whole number; do not include a decimal. A value of 0 indicates no growth. The value can be specified in MB, KB, or %. If a number is specified without an MB, KB, or % suffix, the default is MB. When % is specified, the growth increment size is the specified percentage of the size of the file at the time the increment occurs. If FILEGROWTH is not specified, the default value is 10% and the minimum value is 64 KB. The size specified is rounded to the nearest 64 KB.

_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 34

Bases de Dados II ISEP _________________________________________________________________________________________

3.2 Tipos de dados


Para criao de tabelas existem vrios tipos de dados (numricos, strings, etc.) que podem ser utilizados. Existe tambm a possibilidade de criar novos tipos de dados baseados nos que j existem. 3.2.1 Tipo de dados pr-definidos
Meaning Integer data with either a 1 or 0 value. Integer (whole number) data from -2^31 (-2,147,483,648) through 2^31 - 1 Int (2,147,483,647). Smallint Integer data from 2^15 (-32,768) through 2^15 - 1 (32,767). Tinyint Integer data from 0 through 255. Decimal Fixed precision and scale numeric data from -10^38 -1 through 10^38 -1. Numeric A synonym for decimal. Monetary data values from -2^63 (-922,337,203,685,477.5808) through Money 2^63 - 1 (+922,337,203,685,477.5807), with accuracy to a ten-thousandth of a monetary unit. Monetary data values from -214,748.3648 through +214,748.3647, with Smallmoney accuracy to a ten-thousandth of a monetary unit. Float Floating precision number data from -1.79E + 308 through 1.79E + 308. Real Floating precision number data from -3.40E + 38 through 3.40E + 38. Date and time data from January 1, 1753, to December 31, 9999, with an Datetime accuracy of three-hundredths of a second, or 3.33 milliseconds. Date and time data from January 1, 1900, through June 6, 2079, with an Smalldatetime accuracy of one minute. TimeStamp A database-wide unique number. UniqueIdentifier A globally unique identifier (GUID). Fixed-length non-Unicode character data with a maximum length of 8,000 Char characters. Varchar Variable-length non-Unicode data with a maximum of 8,000 characters. Variable-length non-Unicode data with a maximum length of 2^31 - 1 Text (2,147,483,647) characters. Nchar Fixed-length Unicode data with a maximum length of 4,000 characters. Variable-length Unicode data with a maximum length of 4,000 characters. Nvarchar sysname is a system-supplied user-defined data type that is a synonym for nvarchar(128) and is used to reference database object names. Variable-length Unicode data with a maximum length of 2^30 - 1 Ntext (1,073,741,823) characters. Binary Fixed-length binary data with a maximum length of 8,000 bytes. Varbinary Variable-length binary data with a maximum length of 8,000 bytes. Variable-length binary data with a maximum length of 2^31 - 1 Image (2,147,483,647) bytes Bit
_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 35

Name

Bases de Dados II ISEP _________________________________________________________________________________________

3.2.2 Tipo de dados definidos pelo utilizador Ex. EXEC sp_addtype MyString, varchar(10) Syntax sp_addtype [@typename =] type, [@phystype =] system_data_type [, [@nulltype =] 'null_type'] Arguments
[@typename =] type Is the name of the user-defined data type. Data type names must follow the rules for identifiers and must be unique in each database. type is sysname, with no default. [@phystype =] system_data_type Is the physical, or Microsoft SQL Server-supplied, data type (decimal, int, and so on) on which the user-defined data type is based. system_data_type is sysname, with no default, and can be one of these values: binary(n) image Smalldatetime bit int Smallint char(n) nchar(n) Text datetime ntext Tinyint decimal numeric Uniqueidentifier decimal[(p[, s])] numeric[(p[, s])] varbinary(n) nvarchar(n) varchar(n) float float(n) real Quotation marks are required around all parameters that have embedded blank spaces or punctuation marks. n Is a nonnegative integer indicating the length for the chosen data type p Is a nonnegative integer indicating the maximum total number of decimal digits that can be stored, both to the left and to the right of the decimal point. s Is a nonnegative integer indicating the maximum number of decimal digits that can be stored to the right of the decimal point, and it must be less than or equal to the precision. For more information, see decimal and numeric. [@nulltype =] null_type Indicates the way the user-defined data type handles null values. null_type is varchar(8), with a default of NULL, and must be enclosed in single quotation marks (NULL, NOT NULL, or NONULL). If null_type is not explicitly defined by sp_addtype, it is set to the current default nullability. Use the GETANSINULL system
_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 36

Bases de Dados II ISEP _________________________________________________________________________________________

function to determine the current default nullability, which can be adjusted by using the SET statement or sp_dboption. Nullability should be explicitly defined.

Nota : Para apagar utiliza-se a stored procedure sp_droptype, ex. EXEC sp_droptype MyString

3.3 Tabelas
As tabelas so objectos da BD que contm os dados. Uma tabela um conjunto de colunas, em que cada coluna tem que ter um nome nico na tabela. Podem existir nomes de colunas iguais em tabelas diferentes. Para cada coluna necessrio definir o tipo de dados que vai suportar e se aceita ou no valores nulos. No SQL Server possvel : Existirem mais de 2 bilies de tabelas 1024 colunas em cada tabela 8060 bytes por coluna, excepto para os tipos image e text, que podem ter mais. 1 index clustered(ordem fsica de armazenamento) e 249 no clustered

3.3.1 Criar, alterar e apagar tabelas Ex. CREATE TABLE Cliente (Codigo int, Nome nvarchar(60)) Ex. ALTER TABLE Cliente ADD Pais int Ex. DROP TABLE Cliente

_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 37

Bases de Dados II ISEP _________________________________________________________________________________________

Syntax CREATE TABLE [ database_name.[owner]. | owner. ] table_name ( { <column_definition> | column_name AS computed_column_expression | <table_constraint> } [,...n] ) [ON {filegroup | DEFAULT} ] [TEXTIMAGE_ON {filegroup | DEFAULT} ] <column_definition> ::= { column_name data_type } [ [ DEFAULT constant_expression ] | [ IDENTITY [(seed, increment ) [NOT FOR REPLICATION] ] ] ] [ ROWGUIDCOL ] [ <column_constraint>] [ ...n] <column_constraint> ::= [CONSTRAINT constraint_name] { [ NULL | NOT NULL ] | [ { PRIMARY KEY | UNIQUE } [CLUSTERED | NONCLUSTERED] [WITH FILLFACTOR = fillfactor] [ON {filegroup | DEFAULT} ]] ] | [ [FOREIGN KEY] REFERENCES ref_table [(ref_column) ] [NOT FOR REPLICATION] ] | CHECK [NOT FOR REPLICATION] (logical_expression) } <table_constraint> ::= [CONSTRAINT constraint_name] { [ { PRIMARY KEY | UNIQUE } [ CLUSTERED | NONCLUSTERED] { ( column[,...n] ) } [ WITH FILLFACTOR = fillfactor]
_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 38

Bases de Dados II ISEP _________________________________________________________________________________________

[ON {filegroup | DEFAULT} ] ] | FOREIGN KEY [(column[,...n])] REFERENCES ref_table [(ref_column[,...n])] [NOT FOR REPLICATION] | CHECK [NOT FOR REPLICATION] (search_conditions) } Arguments
database_name Is the name of the database in which the table is created. database_name must specify the name of an existing database. database_name defaults to the current database if it is not specified. The login for the current connection must be associated with an existing user ID in the database specified by database_name, and that user ID must have create table privileges. owner Is the name of the user ID that owns the new table. owner must be an existing user ID in the database specified by database_name. owner defaults to the user ID associated with the login for the current connection in the database specified in database_name. If the CREATE TABLE statement is executed by a member of the sysadmin fixed server role, or a member of the db_dbowner or db_ddladmin fixed database roles in the database specified by database_name, owner can specify a user ID other than the one associated with the login of the current connection. If the CREATE TABLE statement is executed by a login associated with a user ID that has been granted only create table privileges, owner must specify the user ID associated with the current login. Members of the sysadmin fixed server role, the database owner, or logins aliased to the dbo user are associated with the user ID dbo; therefore, tables created by these users default to having dbo as the owner. Tables created by any logins not in either of these two roles have owner default to the user ID associated with the login. table_name Is the name of the new table. Table names must conform to the rules for identifiers. The combination of owner.table_name must be unique within the database. table_name can contain up to 128 characters, except for local temporary table names (names prefixed with a single number sign (#)) that cannot exceed 116 characters. column_name Is the name of a column in the table. Column names must conform to the rules for identifiers and must be unique in the table. column_name can be omitted for columns created with a timestamp data type. The name of a timestamp column defaults to timestamp if column_name is not specified. computed_column_expression Is an expression defining the value of a computed column. A computed column is a virtual column not physically stored in the table. It is computed from an expression using other columns in the same table. For example, a computed column can have the
_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 39

Bases de Dados II ISEP _________________________________________________________________________________________

definition: cost AS price * qty. The expression can be a noncomputed column name, constant, function, variable, and any combination of these connected by one or more operators. The expression cannot be a subquery. Computed columns can be used in select lists, WHERE clauses, ORDER BY clauses, or any other locations in which regular expressions can be used, with the following exceptions: A computed column cannot be used as a key column in an index or as part of any PRIMARY KEY, UNIQUE, FOREIGN KEY, or DEFAULT constraint definition. A computed column cannot be the target of an INSERT or UPDATE statement. ON {filegroup | DEFAULT} Specifies the filegroup on which the table is stored. If filegroup is specified, the table is stored in the named filegroup. The filegroup must exist within the database. If DEFAULT is specified, or if ON is not specified at all, the table is stored on the default filegroup. ON {filegroup | DEFAULT} can also be specified in a PRIMARY KEY or UNIQUE constraint. These constraints create indexes. If filegroup is specified, the index is stored in the named filegroup. If DEFAULT is specified, the index is stored in the default filegroup. If no filegroup is specified in a constraint, the index is stored on the same filegroup as the table. If the PRIMARY KEY or UNIQUE constraint creates a clustered index, the data pages for the table are stored in the same filegroup as the index. TEXTIMAGE_ON Are keywords indicating that the text, ntext, and image columns are stored on the specified filegroup. TEXTIMAGE ON is not allowed if there are no text, ntext, or image columns in the table. If TEXTIMAGE_ON is not specified, the text, ntext, and image columns are stored in the same filegroup as the table. data_type Specifies the data type of the column. System or user-defined data types are acceptable. User-defined data types are created with sp_addtype before they can be used in a table definition. The NULL/NOT NULL assignment for a user-defined data type can be overridden during the CREATE TABLE statement. However, the length specification cannot be changed; you cannot specify a length for a user-defined data type in a CREATE TABLE statement. DEFAULT Specifies the value provided for the column when a value is not explicitly supplied during an insert. DEFAULT definitions can be applied to any columns except those defined as timestamp, or those with the IDENTITY property. DEFAULT definitions are removed when the table is dropped. Only a constant value, such as a character string; a system function, such as SYSTEM_USER(); or NULL can be used as a default. To maintain compatibility with earlier versions of SQL Server, a constraint name can be assigned to a DEFAULT. constant_expression Is a constant, NULL, or a system function used as the default value for the column. IDENTITY Indicates that the new column is an identity column. When a new row is added to the table, Microsoft SQL Server provides a unique, incremental value for the column.
_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 40

Bases de Dados II ISEP _________________________________________________________________________________________

Identity columns are commonly used in conjunction with PRIMARY KEY constraints to serve as the unique row identifier for the table. The IDENTITY property can be assigned to tinyint, smallint, int, decimal(p,0), or numeric(p,0) columns. Only one identity column can be created per table. Bound defaults and DEFAULT constraints cannot be used with an identity column. You must specify both the seed and increment or neither. If neither is specified, the default is (1,1). seed Is the value that is used for the very first row loaded into the table. increment Is the incremental value that is added to the identity value of the previous row that was loaded. NOT FOR REPLICATION Indicates that the IDENTITY property should not be enforced when a replication login such as sqlrepl inserts data into the table. Replicated rows must retain the key values they were assigned in the publishing database, the NOT FOR REPLICATION clause ensures that rows inserted by a replication process are not assigned new identity values. Rows inserted by other logins continue to have new identity values created in the usual way. It is recommended that a CHECK constraint with NOT FOR REPLICATION also be defined to ensure that the identity values being assigned are within the range wanted for the current database. ROWGUIDCOL Indicates that the new column is a row global unique identifier column. Only one uniqueidentifier column per table can be designated as the ROWGUIDCOL column. The ROWGUIDCOL property can be assigned only to a uniqueidentifier column. The ROWGUIDCOL keyword is not valid if the database compatibility level is 65 or lower. The ROWGUIDCOL property does not enforce uniqueness of the values stored in the column. It also does not automatically generate values for new rows inserted into the table. To generate unique values for each column, either use the NEWID function on INSERT statements or use the NEWID function as the default for the column. CONSTRAINT Is an optional keyword indicating the beginning of a PRIMARY KEY, NOT NULL, UNIQUE, FOREIGN KEY, or CHECK constraint definition. Constraints are special properties that enforce data integrity and create special types of indexes for the table and its columns. constraint_name Is the name of a constraint. Constraint names must be unique within a database. NULL | NOT NULL Are keywords that determine whether or not null values are allowed in the column. NULL is not strictly a constraint, but can be specified in the same manner as NOT NULL. PRIMARY KEY Is a constraint that enforces entity integrity for a given column or columns through a unique index. Only one PRIMARY KEY constraint can be created per table. UNIQUE Is a constraint that provides entity integrity for a given column or columns through a unique index. A table can have multiple UNIQUE constraints.
_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 41

Bases de Dados II ISEP _________________________________________________________________________________________

CLUSTERED | NONCLUSTERED Are keywords to indicate that a clustered or a nonclustered index is created for the PRIMARY KEY or UNIQUE constraint. PRIMARY KEY constraints default to CLUSTERED and UNIQUE constraints default to NONCLUSTERED. You can specify CLUSTERED for only one constraint in a CREATE TABLE statement. If you specify CLUSTERED for a UNIQUE constraint and also specify a PRIMARY KEY constraint, the PRIMARY KEY defaults to NONCLUSTERED. [WITH FILLFACTOR = fillfactor] Specifies how full SQL Server should make each index page used to store the index data. User-specified fillfactor values can be from 1 through 100, with a default of 0. A lower fill factor creates the index with more space available for new index entries without having to allocate new space. FOREIGN KEY...REFERENCES Is a constraint that provides referential integrity for the data in the column or columns. FOREIGN KEY constraints require that each value in the column exists in the corresponding referenced column(s) in the referenced table. FOREIGN KEY constraints can reference only columns that are PRIMARY KEY or UNIQUE constraints in the referenced table. ref_table Is the name of the table referenced by the FOREIGN KEY constraint. (ref_column[,...n]) Is a column, or list of columns, from the table referenced by the FOREIGN KEY constraint. CHECK Is a constraint that enforces domain integrity by limiting the possible values that can be entered into a column or columns. NOT FOR REPLICATION Keywords used to prevent the CHECK constraint from being enforced during the distribution process used by replication. When tables are Subscribers to a replication publication, do not update the subscription table directly, instead update the publishing table, and let replication distribute the data back to the subscribing table. A CHECK constraint can be defined on the subscription table to prevent users from modifying it. Unless the NOT FOR REPLICATION clause is added, however, the CHECK constraint also prevents the replication process from distributing modifications from the publishing table to the subscribing table. The NOT FOR REPLICATION clause means the constraint is enforced on user modifications, but not on the replication process. The NOT FOR REPLICATION CHECK constraint is applied to both the before and after image of an updated record to prevent records from being added to or deleted from the replicated range. All deletes and inserts are checked; if they fall within the replicated range, they are rejected. logical_expression Is a logical expression that returns TRUE or FALSE. column Is a column, or list of columns, in parentheses used in table constraints to indicate the columns that are used in the constraint definition. n Is a placeholder indicating that the preceding item can be repeated n number of times.
_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 42

Bases de Dados II ISEP _________________________________________________________________________________________

3.4 Integridade da BD
Uma das fases mais importantes no desenho da BD definir a integridade dos dados, ou seja, garantir o mximo possvel de regras de validao para os dados que vo ser manipulados.

3.4.1 Tipos de integridade Os diferentes tipos de integridade podem ser classificados em trs categorias: Integridade da entidade - A integridade de uma entidade permite definir que numa tabela cada registo nico. Este tipo de integridade pode ser definido atravs de uma chave primria, indexes nicos e atravs da propriedade Identity. Integridade de domnio - A integridade de um domnio permite definir validaes para uma determinada coluna. Pode ser definido o tipo de dados, o formato, um intervalo de valores possveis atravs de Foreign Keys, Check Constraints, valores default, definio de Not Null e regras. Integridade referencial - A integridade relacional assegura que as relaes entre duas tabelas (chave primria e chave estrangeira) sejam preservadas, ou seja, no possvel inserir existir uma chave estrangeira que no tenha uma valor na chave primria, nem possvel apagar um registo da chave primria se j existirem chaves estrangeiras para esse registo.

_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 43

Bases de Dados II ISEP _________________________________________________________________________________________

3.4.2 Definio de Constraints Os constraints so definidos atravs dos comando Create Table e Alter Table. Podem ser definidos para uma ou vrias colunas da tabela. Syntax incompleta CREATE TABLE table_name ( { <column_definition> | column_name AS computed_column_expression | <table_constraint> } [,...n] ) <column_definition> ::= { column_name data_type } [ [ DEFAULT constant_expression ] [ <column_constraint>] [ ...n] <column_constraint> ::= [CONSTRAINT constraint_name] { [ NULL | NOT NULL ] | [ { PRIMARY KEY | UNIQUE }[CLUSTERED | NONCLUSTERED]]] | [ [FOREIGN KEY] REFERENCES ref_table [(ref_column) ]] | CHECK (logical_expression) } <table_constraint> ::= [CONSTRAINT constraint_name] { [ { PRIMARY KEY | UNIQUE } [ CLUSTERED | NONCLUSTERED] { ( column[,...n] ) }] | FOREIGN KEY [(column[,...n])] REFERENCES ref_table [(ref_column[,...n])] | CHECK (search_conditions) } Argumentos incompletos
DEFAULT Specifies the value provided for the column when a value is not explicitly supplied during an insert.

_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 44

Bases de Dados II ISEP _________________________________________________________________________________________

CONSTRAINT Is an optional keyword indicating the beginning of a PRIMARY KEY, NOT NULL, UNIQUE, FOREIGN KEY, or CHECK constraint definition. Constraints are special properties that enforce data integrity and create special types of indexes for the table and its columns. NULL | NOT NULL Are keywords that determine whether or not null values are allowed in the column. NULL is not strictly a constraint, but can be specified in the same manner as NOT NULL. PRIMARY KEY Is a constraint that enforces entity integrity for a given column or columns through a unique index. Only one PRIMARY KEY constraint can be created per table. UNIQUE Is a constraint that provides entity integrity for a given column or columns through a unique index. A table can have multiple UNIQUE constraints. CHECK Is a constraint that enforces domain integrity by limiting the possible values that can be entered into a column or columns. FOREIGN KEY...REFERENCES Is a constraint that provides referential integrity for the data in the column or columns. FOREIGN KEY constraints require that each value in the column exists in the corresponding referenced column(s) in the referenced table. FOREIGN KEY constraints can reference only columns that are PRIMARY KEY or UNIQUE constraints in the referenced table.

_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 45

Bases de Dados II ISEP _________________________________________________________________________________________

Ex. CREATE TABLE Factura (nmero INT NOT NULL CONSTRAINT c_nmero PRIMARY KEY, valor FLOAT) CREATE TABLE linhas (nmero INT NOT NULL REFERENCES Factura(nmero), linha INT NOT NULL CHECK (linha < 99) CONSTRAINT c_linhas PRIMARY KEY(nmero, linha)) Testar com: insert into linhas values(1,1) Erro : Porque no existe ainda a factura 1 insert into factura values(1,1) insert into factura values(1,1) Erro : Porque j existe a factura 1 insert into linhas values(1,10) insert into linhas values(1,11) insert into linhas values(1,10) Erro : Porque j existe a linha 10 da factura 1 insert into linhas values(1,100) Erro : Porque a linha s suporta valores inferiores a 99 delete from factura Erro : Porque existem linhas delete from linhas delete from factura

_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 46

Bases de Dados II ISEP _________________________________________________________________________________________

3.4.3 Defaults Os Defaults permitem especificar que valor fica guardado numa coluna, quando este no especificado ao inserir um registo. Os defaults podem ser criados no momento da criao de uma tabela ou atravs do objecto Default. 3.4.3.1 Definio de defaults possvel definir um default para cada coluna de uma tabela acrescentado o comando Default seguido do valor do default. Ex. CREATE TABLE cliente (codigo int DEFAULT 0, Nome Varchar(40), DataEntrada DateTime DEFAULT getdate() ) INSERT INTO cliente (Nome) VALUES (teste)

3.4.3.2 Objecto Default possvel definir vrios objectos defaults que podero ser usados em vrias colunas de tabelas. Ex. CREATE DEFAULT Nome AS 'desconhecido' // DROP DEFAULT Nome CREATE TABLE Cliente(cod int, Nome Varchar(20), Zona int) sp_bindefault Nome, 'cliente.nome' //sp_unbindefault 'cliente.nome' INSERT INTO cliente (cod) VALUES (2)

Syntax CREATE DEFAULT default AS constant_expression Arguments


default Is the name of the default. Default names must conform to the rules for identifiers. Specifying the default owner name is optional. constant_expression Is an expression that contains only constant values (it cannot include the names of any columns or other database objects). Any constant, built-in function, or mathematical expression can be used. Enclose character and date constants in single quotation marks (); monetary, integer, and floating-point constants do not require quotation marks. Binary data must be preceded by 0x, and monetary data must be preceded by a dollar sign ($). The default value must be compatible with the data type of the column.
_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 47

Bases de Dados II ISEP _________________________________________________________________________________________

3.4.4 Rules O comando Rule permite definir regras de validao para as colunas das tabelas. Ex. CREATE RULE regra_codigo AS @x >= 0 AND @x < 99 //DROP RULE regra_codigo sp_bindrule regra_codigo, 'cliente.cod' //sp_unbindrule regra_codigo, 'cliente.cod' INSERT INTO cliente (cod) VALUES (777) Ex. CREATE RULE RegraZona AS @Z IN (1, 2, 3) sp_bindrule regraZona, 'cliente.zona'

3.5 Base de dados Mercado


create Database BD2 go use BD2 CREATE TABLE Familias ( FamiliaID int NOT NULL , Descricao varchar (40) NOT NULL ) CREATE TABLE Clientes ( ClienteID int NOT NULL , Nome varchar (40) NOT NULL , Morada1 varchar (40) NULL , Morada2 varchar (40) NULL , CodPostal varchar (40) NULL , EMail varchar (40) NULL, DataNasc DateTime NULL, ZonaID int )
_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 48

Bases de Dados II ISEP _________________________________________________________________________________________

CREATE TABLE LinhasFact ( FactID int NOT NULL , LinhaID int NOT NULL, ArtigoID varchar(10) NOT NULL , Preco money NOT NULL , Quant smallint NOT NULL , Desconto real NOT NULL ) CREATE TABLE Facts ( FactID int IDENTITY (1, 1) NOT NULL , ClienteID int NOT NULL , Data datetime NULL , DataVenc datetime NULL ) CREATE TABLE Artigos ( ArtigoID varchar(10) NOT NULL , Descricao nvarchar (40) NOT NULL , FamiliaID int NULL , PrecoCompra money NULL , PrecoVenda money NULL , Existencias smallint NULL ) CREATE TABLE Arvore ( CodPai Varchar(10) NOT NULL , CodFilho Varchar (10) NOT NULL , Qtd real NOT NULL ) CREATE TABLE Zona ( ZonaID int NOT NULL , Descricao nvarchar (40) NOT NULL )

_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 49

Bases de Dados II ISEP _________________________________________________________________________________________

3.6 Integridadade da BD Mercado


/* Criao de chaves primrias para todas as tabelas */ ALTER TABLE Familias ADD CONSTRAINT PK_Familias PRIMARY KEY CLUSTERED ( FamiliaID )

ALTER TABLE Clientes ADD CONSTRAINT PK_Clientes PRIMARY KEY NONCLUSTERED ( ClienteID )

ALTER TABLE LinhasFact ADD CONSTRAINT PK_LinhasFact PRIMARY KEY NONCLUSTERED ( FactID, LinhaID ) ALTER TABLE Facts ADD CONSTRAINT PK_Facts PRIMARY KEY NONCLUSTERED ( FactID ) ALTER TABLE Artigos ADD CONSTRAINT PK_Artigos PRIMARY KEY NONCLUSTERED ( ArtigoID )

ALTER TABLE Zona WITH NOCHECK ADD CONSTRAINT PK_Zona PRIMARY KEY CLUSTERED ( ZonaID )
_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 50

Bases de Dados II ISEP _________________________________________________________________________________________

ALTER TABLE Arvore WITH NOCHECK ADD CONSTRAINT PK_Arvore PRIMARY KEY NONCLUSTERED (CodPai, CodFilho) /* Na tabela LinhasFact : - Se o Preo no introduzido, assumir por defeito 0 - Se a Quantidade no introduzida, assumir por defeito 1 - Se o Desconto no introduzido, assumir por defeito 0 - O Desconto s pode aceitar valores entre 0 e 100. - A Quantidade sempre maior que 0. O Preo sempre maior ou igual a 0. */ ALTER TABLE LinhasFact ADD CONSTRAINT DF_LinhasFact_Preco DEFAULT (0) FOR Preco, CONSTRAINT DF_LinhasFact_Quant DEFAULT (1) FOR Quant, CONSTRAINT DF_LinhasFact_Desconto DEFAULT (0) FOR Desconto, CONSTRAINT CK_Desconto CHECK (Desconto >= 0 and Desconto <= 100), CONSTRAINT CK_Quant CHECK (Quant > 0), CONSTRAINT CK_Preco CHECK (Preco >= 0) /* Na tabela Artigos : - Se os Preos no forem introduzidos, assumir por defeito 0 - Se a Existncia no introduzida, assumir por defeito 0 - A Existncia sempre maior ou igual 0. - Os Preos so sempre maior ou igual a 0. */

/* Criar chave estrangeira nas LinhasFact para a tabela Facts */ /* Criar chave estrangeira nas LinhasFact para a tabela Artigos */

_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 51

Bases de Dados II ISEP _________________________________________________________________________________________

/* Criar chave estrangeira na tabela Fact para a tabela Cliente */ ALTER TABLE Facts ADD CONSTRAINT FK_Facts_Clientes FOREIGN KEY ( ClienteID ) REFERENCES Clientes ( ClienteID ) /* Criar chave estrangeira na tabela Artigos para a tabela Familia */

/* Criar chave estrangeira na Clientes para a tabela Zona */

/* Criar chaves estrangeiras na tabela Arvore para a tabela Artigo */

/* Na tabela Arvore : - Se a Quantidade no introduzida, assumir por defeito 1 - A Quantidade sempre maior que 0. */
_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 52

Bases de Dados II ISEP _________________________________________________________________________________________

insert into familias values(1, 'Calas') insert into familias values(2, 'Camisolas') insert into familias values(3, 'Blusas') insert into familias values(4, 'Sapatos') insert into familias values(5, 'camisas') insert into familias values(6, 'producao') insert into zona values(1, 'Norte') insert into zona values(2, 'Centro') insert into zona values(3, 'Sul') insert into clientes values(1, 'Antnio', 'Porto', '','4200', 'ant@mail.pt', '1960/11/01', 1) insert into clientes values(2, 'Afonso', 'Lisboa', '','4200', 'afo@mail.pt', '1980/01/11', 3) insert into clientes values(3, 'Susana', 'Coimbra', '','4200', 'sus@mail.pt', '1975/05/01',2) insert into clientes values(4, 'Mrio', 'Faro', '','4200', 'mar@mail.pt', '1982/01/01', 3) insert into clientes values(5, 'Paulo', 'Porto', '','4200', 'pau@mail.pt', '1976/01/01', 1) insert into clientes values(6, 'Serafim', 'Porto', '','4200', 'ser@mail.pt', '1960/08/01', 1) insert into clientes values(7, 'Alexandre', 'Porto', '','4200', 'ale@mail.pt', '1967/05/01',1)
_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 53

Bases de Dados II ISEP _________________________________________________________________________________________

insert into artigos values(1, 'Cala ganga preta', 1, 12000, 15000,100) insert into artigos values(2, 'Cala ganga azul', 1, 13000, 14000, 100) insert into artigos values(3, 'Cala ganga branca', 1, 12500, 13500,100) insert into artigos values(4, 'Camisa ganga preta', 5, 6000, 8000,100) insert into artigos values(5, 'Camisa azul', 5, 5000, 6000,100) insert into artigos values(6, 'Sapatos XY', 4, 12000, 13000,100) insert into artigos values(7, 'Blusa Vermelha', 1, 7000, 8000, 100) insert into artigos values(8, 'Camisola preta', 1, 8000, 9500,100) insert into artigos values(9, 'Camisola azul', 1, 8500, 9990,100) insert into artigos values ('A', 'Artigo A', 6, null, null,null) insert into artigos values ('B', 'Artigo B', 6, 100, null,null) insert into artigos values ('C', 'Artigo C',6,null, null,null) insert into artigos values ('D', 'Artigo D', 6, null, null,null) insert into artigos values ('E', 'Artigo E', 6, 40, null,null) insert into artigos values ('F', 'Artigo F', 6, 150,null,null) insert into artigos values ('G', 'Artigo G', 6, 400, null,null) insert into artigos values ('H', 'H', 6, 20, null,null) INSERT INTO Arvore(CodPai, CodFilho, Qtd) VALUES('A','B', 2) INSERT INTO Arvore(CodPai, CodFilho, Qtd) VALUES('A','C', 4) INSERT INTO Arvore(CodPai, CodFilho) VALUES('A','D') INSERT INTO Arvore(CodPai, CodFilho, Qtd) VALUES('C','E', 2) INSERT INTO Arvore(CodPai, CodFilho, Qtd) VALUES('C','F', 2) INSERT INTO Arvore(CodPai, CodFilho) VALUES('D','H')

/* No insere o campo IDENTITY */ insert into facts values(1, '1998/01/01', '1998/01/01') insert into facts values(1, '1998/02/01', '1998/03/01') insert into facts values(2, '1995/02/01', '1995/04/01') insert into facts values(4, '1991/02/01', '1991/03/01') insert into facts values(1, '1998/02/01', '1998/03/01') insert into facts values(7, '1997/02/01', '1997/03/01') insert into linhasFact values(1, 1, 1, 12000, 5, 10) insert into linhasFact values(1, 2, 4, 6000, 3, 0) insert into linhasFact values(1, 3, 5, 12000, 1, 10) insert into linhasFact values(2, 1, 2, 12000, 5, 0) insert into linhasFact values(2, 2, 4, 11000, 1, 0) insert into linhasFact values(3, 1, 2, 2000, 5, 0) insert into linhasFact values(3, 2, 4, 1000, 1, 0) insert into linhasFact values(4, 1, 5, 12000, 5, 0) insert into linhasFact values(5, 1, 7, 7000, 1, 0) insert into linhasFact values(6, 1, 8, 12000, 5, 0) insert into linhasFact values(6, 2, 9, 11000, 1, 0)

_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 54

Bases de Dados II ISEP _________________________________________________________________________________________

3.7 Indexes
O modo de funcionamento bsico dos indexes na base de dados so semelhantes aos de um livro. Num livro, um ndice permite encontrar rapidamente informao sem haver a necessidade de ler todo o livro, pois o ndice tem a informao organizada. Nas bases de dados igual, quando h necessidade de encontrar informao, se no existir um index, a base de dados ter que percorrer todos os registos da tabela, de uma forma sequencial, at encontrar o que quer.

As vantagens da utilizao de indexes so : Rapidez de acesso aos dados Garante a integridade de dados (unique indexes) As desvantagens so : Gastam espao em disco Gasto de tempo em manuteno Ex. CREATE UNIQUE INDEX C1 ON Cliente(Nome)

_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 55

Bases de Dados II ISEP _________________________________________________________________________________________

Syntax incompleta CREATE [UNIQUE] [CLUSTERED | NONCLUSTERED] INDEX index_name ON table (column [,...n]) Arguments
UNIQUE Creates a unique index (one in which no two rows are permitted to have the same index value). Microsoft SQL Server checks for duplicate values when the index is created (if data already exists) and checks each time data is added with an INSERT or UPDATE statement. If duplicate key values exist, the CREATE INDEX statement is canceled and an error message giving the first duplicate is returned. A unique index cannot be created on a single column or multiple columns (composite index) in which the complete key (all columns of that key) is NULL in more than one row; these are treated as duplicate values for indexing purposes. When a unique index exists, UPDATE or INSERT statements that would generate duplicate key values are rolled back, and SQL Server displays an error message. CLUSTERED Creates an object where the physical order of rows is the same as the indexed order of the rows, and the bottom (leaf) level of the clustered index contains the actual data rows. Because nonclustered indexes are rebuilt when a clustered index is created, create the clustered index before creating any nonclustered indexes. If CLUSTERED is not specified, a nonclustered index is created. NONCLUSTERED Creates an object that specifies the logical ordering of a table. With a nonclustered index, the physical order of the rows is not the same as their indexed order. The leaf level of a nonclustered index contains index rows. Each index row contains the nonclustered key value and one or more row locators that point to the row that contains the value. If the table does not have a clustered index, the row locator is the rows disk address. If the table does have a clustered index, the row locator is the clustered index key for the row. Each table can have as many as 249 nonclustered indexes (regardless of how they are created: implicitly with PRIMARY KEY and UNIQUE constraints, or explicitly with CREATE INDEX). Each index can provide access to the data in a different sort order. index_name Is the name of the index. Index names must be unique within a table but need not be unique within a database. Index names must follow the rules of identifiers. table Is the table that contains the column or columns to be indexed. Specifying the database and table owner names is optional. column Is the column or columns to which the index applies. Specify two or more column names to create a composite index on the combined values in the specified columns. List the columns to be included in the composite index (in sort-priority order) inside the parentheses after table.
_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 56

Bases de Dados II ISEP _________________________________________________________________________________________

3.7.1 Clustered Indexes Um clustered index determina a ordem fsica dos registo numa tabela. Por isso, s possvel ter um clustered index por tabela, mas este index pode ter mais que uma coluna. Os clustered indexes devem ser usados quando : Colunas que tenham um nmero limitado de valores distintos, como os estados dos EUA (50). Mas, se existirem poucos valores (ex. 0 e 1) no dever ser criado um index. Queries que retornam um intervalo de valores aquando da utilizao dos operadores, > e <. Colunas que so acedidas sequencialmente. Colunas que so frequentemente acedidas envolvendo condies de Join ou de Group By, pois como os registos j esto ordenados, implica um aumento de performance. Tabelas que trabalhem muito com operaes de lock, ficam mais rpidas quando utilizam um index clustered, normalmente o Primary Key. Os clustered indexes no devem ser usados quando : Contenham colunas que tenham alteraes frequentes, pois implica mover fisicamente os registos na BD. Tm muitas colunas, pois maior ser a possibilidade de alterar a sua posio fsica.

3.7.2 Nonclustered Indexes Os nonclustered indexes so semelhantes aos clustered indexes apenas com as seguintes diferenas : No implicam que os registos da tabela fiquem ordenados fsicamente Podem existir at 249 por tabela Devem ser utilizados em colunas que : Contenham um grande nmero de valores distintos. Estejam frequentemente em operaes de pesquisa.

_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 57

Bases de Dados II ISEP _________________________________________________________________________________________

3.7.3 Criao de indexes na BD Mercado


/* Criar indexes para o campo Nome na tabela Clientes */ /* Criar indexes para o campo ZonaID na tabela Clientes */ /* Criar indexes para o campo ArtigoID na tabela LinhasFact */ /* Criar indexes para o campo ClienteID na tabela Facts */ CREATE CREATE CREATE CREATE INDEX ClienteNome ON Clientes(Nome) INDEX ClienteZonaID ON Clientes(ZonaID) INDEX LinhasFactArtigoID ON LinhasFact(ArtigoID) INDEX FactClienteID ON Facts(ClienteID)

_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 58

Bases de Dados II ISEP _________________________________________________________________________________________

4. Acesso a dados
O acesso aos dados armazenados nas BD feito atravs do comando Select. A syntax completa deste comando um pouco complexa, mas poder ser resumida as seguintes opes : SELECT select_list [INTO new_table_name] FROM table_list [WHERE search_conditions] [GROUP BY group_by_list] [HAVING search_conditions] [ORDER BY order_list [ASC | DESC] ]
select_list Describes the columns of the result set. It is a comma-separated list of expressions. Each expression defines both the format (data type and size) and the source of the data for the result set column. Each select list expression is usually a reference to a column in the source table or view the data is coming from, but can be any other expression, such as a constant or a Transact-SQL function. Using the * expression in a select list specifies that all columns in the source table are returned. INTO new_table_name Specifies that the result set is used to create a new table. new_table_name specifies the name of the new table. FROM table_list Contains a list of the tables from which the result set data is retrieved. These sources can be: Base tables in the local server running Microsoft SQL Server. Views in the local SQL Server. SQL Server internally resolves a view reference to references against the base tables that make up the view. Linked tables, which are tables in OLE DB data sources made accessible to SQL Server. This is called a distributed query. OLE DB data sources can be accessed from SQL Server by linking them as a linked server, or referencing the data source in an OPENROWSET or OPENQUERY function. The FROM clause can also contain join specifications, which define the specific path SQL Server is to use in navigating from one table to another. The FROM clause is also used on the DELETE and UPDATE statements to define the tables that are modified. WHERE search_conditions The WHERE clause is a filter that defines the conditions each row in the source tables must meet to qualify for the SELECT. Only rows that meet the conditions contribute data to the result set. Data from rows that do not meet the conditions are not used. The WHERE clause is also used on the DELETE and UPDATE statements to define the rows in the target tables that are modified. GROUP BY group_by_list
_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 59

Bases de Dados II ISEP _________________________________________________________________________________________

The GROUP BY clause partitions the result set into groups based on the values in the columns of the group_by_list. For example, the Northwind Orders table has three values in ShipVia. A GROUP BY ShipVia clause partitions the result set into three groups, one for each value of ShipVia. HAVING search_conditions The HAVING clause is an additional filter that is applied to the result set. Logically, the HAVING clause filters rows from the intermediate result set built from the application of any FROM, WHERE, or GROUP BY clauses in the SELECT statement. HAVING clauses are most commonly used with a GROUP BY clause, although a GROUP BY clause is not required before a HAVING clause. ORDER BY order_list [ ASC | DESC ] The ORDER BY clause defines the order in which the rows in the result set are sorted. order_list specifies the result set columns that make up the sort list. The ASC and DESC keywords are used to specify if the rows are sorted in ascending or descending sequence. ORDER BY is important because relational theory specifies that the rows in a result set cannot be assumed to have any sequence unless ORDER BY is specified. ORDER BY must be used in any SELECT statement for which the order of the result set rows is important.

Ex. SELECT * FROM Clientes WHERE ClienteId < 10 ORDER BY Nome

4.1 Joins
Com o comando Join possvel extrair informao de duas ou mais tabelas num nico Select, para isso necessrio definir a relao entre elas. Syntax : FROM first_table join_type second_table [ON (join_condition)] join_type specifies what kind of join is performed: an inner, outer, or cross join. join_condition defines the predicate to be evaluated for each pair of joined rows Ex. SELECT FactID, Facts.ClienteID, Nome FROM Facts JOIN Clientes ON (Clientes.ClienteID = Facts.ClienteID)
_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 60

Bases de Dados II ISEP _________________________________________________________________________________________

OU SELECT FactID, F.ClienteID, Nome FROM Facts As F JOIN Clientes As C ON (C.ClienteID = F.ClienteID) OU SELECT FactID, Facts.ClienteID, Nome FROM Facts, Clientes WHERE Clientes.ClienteID = Facts.ClienteID Ex. SELECT Facts.FactID, Clientes.ClienteID, Nome, artigoID FROM Facts JOIN Clientes ON (Facts.ClienteID = Clientes.ClienteID) JOIN LinhasFact ON (Facts.FactID =LinhasFact.FactID) Existem vrios tipos de Join, que permitem especificar os registos a extrair para um determinada relao :
LEFT JOIN or LEFT OUTER JOIN The result set of a left outer join includes all the rows from the left table specified in the LEFT OUTER clause, not just the ones in which the joined columns match. When a row in the left table has no matching rows in the right table, the associated result set row contains null values for all select list columns coming from the right table. RIGHT JOIN or RIGHT OUTER JOIN A right outer join is the reverse of a left outer join. All rows from the right table are returned. Null values are returned for the left table any time a right table row has no matching row in the left table. FULL JOIN or FULL OUTER JOIN A full outer join returns all rows in both the left and right tables. Any time a row has no match in the other table, the select list columns from the other table contain null values. When there is a match between the tables, the entire result set row contains data values from the base tables.

Ex. SELECT OrderID, Customers.CustomerID, CompanyName FROM Orders LEFT JOIN Customers ON (Orders.CustomerID = Customers.CustomerID) WHERE orderID < 10260

_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 61

Bases de Dados II ISEP _________________________________________________________________________________________

4.2 Funes de agregao


As funes de agregao (ex. SUM, AVG, COUNT, MAX E MIN) agrupam um conjunto de valores. Ex. Seleccionar o volume total de facturas TotFact ----------33 SELECT SUM(quant) As TotFact FROM linhasfact Ex. Seleccionar todas as facturas do cliente 1 e respectiva quantidade de factura. FactID TotQt ---------- ----------1 5 5 1

Ex. Seleccionar todas as facturas do cliente 1 com quantidade facturada superior a 3 FactID TotQt ----------- ----------1 5

_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 62

Bases de Dados II ISEP _________________________________________________________________________________________

4.3 SubQueries
Uma subquerie uma instruo de select embutida no meio de uma querie (Select), de um Delete, de um Insert ou de um Update. Ex. Seleccionar todos os artigos, juntamente com o preo mdio de todos os artigos. ArtigoID PrecoVenda PrecoMedio ---------- --------------------- --------------------1 12000.0000 9333.3333 2 13000.0000 9333.3333 3 12500.0000 9333.3333 4 6000.0000 9333.3333 5 5000.0000 9333.3333 6 12000.0000 9333.3333 7 7000.0000 9333.3333 8 8000.0000 9333.3333 9 8500.0000 9333.3333 SELECT ArtigoID, PrecoVenda, (SELECT AVG(PrecoVenda) FROM Artigos) As PrecoMedio FROM Artigos

Ex. Seleccionar todos os artigos cujo preo seja inferior a mdia de preos dos artigos. ArtigoID PrecoVenda ----------- --------------------4 6000.0000 5 5000.0000 7 7000.0000 8 8000.0000 9 8500.0000

_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 63

Bases de Dados II ISEP _________________________________________________________________________________________

Ex. Seleccionar todas as facturas cuja data seja igual a factura com a data mais recente. FactId Data ----------- --------------------------2 1998-02-01 00:00:00.000 5 1998-02-01 00:00:00.000

Ex. Efectuar uma seleco em que conste o produto, a sua quantidade facturada, o total da quantidade facturada, e a percentagem que essa quantidade representa em relao ao total da facturao. ArtigoID TotQt TotQtFact Percentagem ----------- -------- ------------- --------------------1 5 23 21.7300 2 5 23 21.7300 4 1 23 4.3400 5 5 23 21.7300 7 1 23 4.3400 8 5 23 21.7300 9 1 23 4.3400

_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 64

Bases de Dados II ISEP _________________________________________________________________________________________

Ex. Seleccionar o nome de todos os clientes a quem no sejam feitas vendas desde 01/01/1996. ClienteID Nome ----------- ---------------------------------------2 Afonso 3 Susana 4 Mrio 5 Paulo 6 Serafim

4.4 Metacarcteres
Os metacaracteres so utilizados em pesquisas para procurar informao semelhante ao pretendido juntamente com a instruo LIKE. % (percentagem) - Significa qualquer string com zero ou mais caracteres _ (underscore) Significa um nico caracter Ex. Seleccionar todos os produtos cuja descrio comece por Cala ArtigoID Descricao ----------- ---------------------------------------1 Cala ganga preta 2 Cala ganga azul 3 Cala ganga branca

SELECT ArtigoID, Descricao FROM artigos where descricao like "Cala%"

_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 65

Bases de Dados II ISEP _________________________________________________________________________________________

Ex. Selecionar todos os produtos que tenha na sua designao a palavra ganga ArtigoID Descricao ----------- ---------------------------------------1 Cala ganga preta 2 Cala ganga azul 3 Cala ganga branca 4 Camisa ganga preta

Ex. Selecionar todos clientes cujo email termine em @mail.pt e cujo o nome do mail comece em S e tenha s 3 caracteres. clienteID email ----------- ---------------------------------------3 sus@mail.pt 6 ser@mail.pt

Se for necessrio procurar numa string o caracter % preciso colocar um caracter de escape. A instruo para procurar uma coluna a procura de %, seria: coluna LIKE %%% escape Significa que o caracter a seguir ao escape ser interpretado como um caracter normal.
_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 66

Bases de Dados II ISEP _________________________________________________________________________________________

4.5 Unions
Uma union serve para juntar os dados de duas ou mais pesquisas, nessa unio se aparecerem dados repetidos s um deles visualizado. Ex. Mostrar todas as descries de artigos e de familias ordenadas descricao ---------------------------------------Blusa Vermelha Blusas Cala ganga azul Cala ganga branca Cala ganga preta Calas Camisa azul Camisa ganga preta camisas Camisola azul Camisola preta Camisolas Sapatos Sapatos XY SELECT descricao FROM Artigos UNION SELECT descricao FROM familias ORDER BY Descricao

_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 67

Bases de Dados II ISEP _________________________________________________________________________________________

5. Transaes e bloqueamentos
Uma transao uma sequncia de operaes que so executadas como uma s, ou seja, uma transao garante que mltiplas alteraes feitas a bases de dados so efectuadas como um s bloco. As transaes so fundamentais para garantir a consistncia dos dados na BD. Uma transao tem que garantir as propriedades A.C.I.D. Atomicidade Uma transao considerada como um bloco nico para processamento, em que todas as operaes so executadas ou nenhuma , no existe a possibilidade de algumas operaes serem executadas e outras no. Consistncia Quando uma transao est completa, todos os dados tm que ficar consistentes com as regras definidas na base de dados. Isolamento Se existirem transaes concorrentes, elas ficaro isoladas, ou seja, cada transao v os dados na forma original, em nenhuma circunstancia v os dados da outra transao no seu estado intermdio. Durabilidade Aps uma transao estar completa, os seus efeitos sero permanentes (persistentes) no sistema, mesmo que exista falhas no sistema.

As aplicaes controlam as transaes definindo quando elas iniciam e quando acabam. Quando uma transao iniciada, todas as instrues SQL que so executadas, fazem parte dessa transao at a transao terminar. Numa transao possvel utilizar todas as instrues T-SQL excepo de : ALTER DATABASE DROP DATABASE RECONFIGURE BACKUP LOG DUMP TRANSACTION RESTORE DATABASE CREATE DATABASE LOAD DATABASE RESTORE LOG DISK INIT LOAD TRANSACTION
_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 68

Bases de Dados II ISEP _________________________________________________________________________________________

UPDATE STATISTICS

Existem 3 modos distintos para lidar com transaes : Explicit Autocommit Implicit

5.1 Explicit Transactions


Numa transao explicit definido o inicio e o fim da transao. Begin Transaction o comando que permite definir o incio da transao Commit Transaction o comando utilizado para terminar uma transao quando no foram encontrados erros. Rollback Transaction o comando usado para terminar uma transao quando foram encontrados erros. Todas as modificaes feitas durante a transao so desfeitas. Ex. CREATE TABLE Teste (Cod INT PRIMARY KEY, Nome Varchar(30)) BEGIN TRANSACTION INSERT INTO teste VALUES (1, 'valor 1') INSERT INTO teste VALUES (2, 'valor 2') COMMIT TRANSACTION Ex. BEGIN TRANSACTION DELETE FROM teste ROLLBACK TRANSACTION

5.2 Autocommit Transactions


O SQL Server executa por defeito o modo de transao autocommit, ou seja, qualquer instruo efectuada (commit) ou abortada (rollback) quando estiver concluda.
_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 69

Bases de Dados II ISEP _________________________________________________________________________________________

Ex. INSERT INTO Teste VALUES (1, 'valor 1') INSERT INTO Teste VALUES (2, 'Valor 2') INSERT INTO Teste VALUES (1, 'Valor 1 Novamente') Apesar de dar erro na ltima linha, todas as outras ficaram reflectidas na BD.

5.3 Implicit Transactions


No modo de transao implicit, o SQL Server automaticamente inicia uma nova transao aps a ltima ter sido terminada (commit ou rollback), ou seja, no necessrio colocar a instruo Begin Transaction. Para iniciar este modo utiliza-se a instruo SET IMPLICIT_TRANSACTIONS ON, para terminar SET IMPLICIT_TRANSACTIONS OFF. Ex. CREATE TABLE teste2 (Cod int PRIMARY KEY, Nome Varchar(30) NOT NULL) GO SET IMPLICIT_TRANSACTIONS ON GO /* Primeira transao iniciada pela instruo INSERT */ INSERT INTO teste2 VALUES (1, 'aaa') GO INSERT INTO teste2 VALUES (2, 'bbb') GO /* Commit da primeira transao */ COMMIT TRANSACTION GO /* Segunda transao iniciada pela instruo SELECT */ SELECT COUNT(*) FROM ImplicitTran GO INSERT INTO teste2 VALUES (3, 'ccc') GO SELECT * FROM teste2 GO /* Commit da segunda transao */ COMMIT TRANSACTION GO SET IMPLICIT_TRANSACTIONS OFF GO
_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 70

Bases de Dados II ISEP _________________________________________________________________________________________

5.4 Nested Transactions


possvel existirem transaes embutidas dentro de outras transaes, para isso utiliza-se o mesmo comando de inicio, o Begin Transaction. Sempre que for encontrado o comando Commit Transaction, ser referente ao ltimo Begin. Ao utilizar o comando Rollback sero desfeitas todas as operaes efectuadas (no apenas a ltima) a no ser que seja especificado um SavePoint com o comando Save Transaction, nesse caso possvel efectuar um Rollback at esse ponto. Ex. DELETE FROM TESTE BEGIN TRANSACTION XX Insert into teste values (1, 'xxxx') BEGIN TRANSACTION YY Insert into teste values (2, 'xxxx') ROLLBACK TRANSACTION COMMIT TRANSACTION XX D um erro na ltima instruo, pois a penltima instruo fez Rollback de todas as instrues anteriores. Ex. DELETE FROM TESTE BEGIN TRANSACTION XX Insert into teste values (1, 'xxxx') BEGIN TRANSACTION YY Insert into teste values (2, 'xxxx') COMMIT TRANSACTION YY COMMIT TRANSACTION Ex. DELETE FROM TESTE BEGIN TRANSACTION XX Insert into teste values (1, 'xxxx') BEGIN TRANSACTION YY Insert into teste values (2, 'xxxx') COMMIT TRANSACTION YY ROLLBACK TRANSACTION
_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 71

Bases de Dados II ISEP _________________________________________________________________________________________

Ex. BEGIN TRANSACTION XX Insert into teste values (1, 'xxxx') SAVE TRANSACTION ponto1 Insert into teste values (2, 'xxxx') ROLLBACK TRANSACTION ponto1 COMMIT TRANSACTION

5.5 Bloqueamentos
O SQL Server utiliza o processo de bloqueamento (locks) para garantir a integridade e consistncia da BD. O lock evita que os utilizadores acedam a dados que esto a ser alterados por outros, e que alterem os mesmos dados ao mesmo tempo. O SQL Server utiliza dois processos para controlar o acesso mltiplo a um registo : Pessimistic o default do SQL Server, os dados so bloqueados durante toda a transao. Optimistic Pode ser utilizada com os cursores, este processo de bloqueamento baseado no princpio de que anormal (mas no impossvel) que determinados dados sejam acedidos ao mesmo tempo por vrios utilizadores. Apenas no momento da actualizao que determinado se os dados foram alterados entretanto, se assim aconteceu o programador/utilizador que decide o que fazer aos dados, se altera por cima, se no altera ou se altera parcialmente.

_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 72

Bases de Dados II ISEP _________________________________________________________________________________________

6. Cursors
Os registos retornados por uma instruo SQL podem ser manipulados atravs de um cursor. Um cursor semelhante a uma lista de valores, sendo possvel percorrer e posicionar em qualquer um dos registos. Ex. DECLARE Clientes CURSOR FOR SELECT * FROM Clientes

SQL-92 Syntax DECLARE cursor_name [INSENSITIVE] [SCROLL] CURSOR FOR select_statement [FOR {READ ONLY | UPDATE [OF column_name [,...n]]}] Transact-SQL Extended Syntax DECLARE cursor_name CURSOR [LOCAL | GLOBAL] [FORWARD_ONLY | SCROLL] [STATIC | KEYSET | DYNAMIC | FAST_FORWARD] [READ_ONLY | SCROLL_LOCKS | OPTIMISTIC] [TYPE_WARNING] FOR select_statement [FOR UPDATE [OF column_name [,...n]]] SQL-92 Arguments cursor_name Is the name of the Transact-SQL server cursor being defined. cursor_name must conform to the rules for identifiers. INSENSITIVE Defines a cursor that makes a temporary copy of the data to be used by the cursor. All requests to the cursor are answered from this temporary table in tempdb; therefore, modifications made to base tables are not reflected in the data returned by fetches made to this cursor, and this cursor does not allow modifications. When SQL-92 syntax is used, if INSENSITIVE is omitted, committed deletes and updates made to the underlying tables (by any user) are reflected in subsequent fetches. SCROLL Specifies that all fetch options (FIRST, LAST, PRIOR, NEXT, RELATIVE, ABSOLUTE) are available. If SCROLL is not specified in an SQL-92 DECLARE CURSOR, NEXT is the only fetch option supported. SCROLL cannot be specified if FAST_FORWARD is also specified.
_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 73

Bases de Dados II ISEP _________________________________________________________________________________________

select_statement Is a standard SELECT statement that defines the result set of the cursor. The keywords COMPUTE, COMPUTE BY, FOR BROWSE, and INTO are not allowed within select_statement of a cursor declaration. Microsoft SQL Server implicitly converts the cursor to another type if clauses in select_statement conflict with the functionality of the requested cursor type. READ ONLY Prevents updates from being made through this cursor. The cursor cannot be referenced in a WHERE CURRENT OF clause in an UPDATE or DELETE statement. This option overrides the default capability of a cursor to be updated. UPDATE [OF column_name [,...n]] Defines updatable columns within the cursor. If OF column_name [,...n] is specified, only the columns listed allow modifications. If UPDATE is specified without a column list, all columns can be updated.

Transact-SQL Extended Arguments cursor_name Is the name of the Transact-SQL server cursor being defined. cursor_name must conform to the rules for identifiers. LOCAL Specifies that the scope of the cursor is local to the batch, stored procedure, or trigger in which the cursor was created. The cursor name is only valid within this scope. The cursor can be referenced by local cursor variables in the batch, stored procedure, or trigger, or a stored procedure OUTPUT parameter. An OUTPUT parameter is used to pass the local cursor back to the calling batch, stored procedure, or trigger, which can assign the parameter to a cursor variable to reference the cursor after the stored procedure terminates. The cursor is implicitly deallocated when the batch, stored procedure, or trigger terminates, unless the cursor was passed back in an OUTPUT parameter. If it is passed back in an OUTPUT parameter, the cursor is deallocated when the last variable referencing it is deallocated or goes out of scope. GLOBAL Specifies that the scope of the cursor is global to the connection. The cursor name can be referenced in any stored procedure or batch executed by the connection. The cursor is only implicitly deallocated at disconnect. FORWARD_ONLY Specifies that the cursor can only be scrolled from the first to the last row. FETCH NEXT is the only supported fetch option. If FORWARD_ONLY is specified without the STATIC, KEYSET, or DYNAMIC keywords, the cursor operates as a DYNAMIC cursor. When neither FORWARD_ONLY nor SCROLL is specified, FORWARD_ONLY is the default, unless the keywords STATIC, KEYSET, or DYNAMIC are specified. STATIC, KEYSET, and DYNAMIC cursors default to SCROLL. Unlike database APIs such as ODBC and ADO, FORWARD_ONLY is supported with STATIC, KEYSET, and DYNAMIC Transact-SQL cursors. FAST_FORWARD and FORWARD_ONLY are mutually exclusive, if one is specified the other cannot be specified.
_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 74

Bases de Dados II ISEP _________________________________________________________________________________________

STATIC Defines a cursor that makes a temporary copy of the data to be used by the cursor. All requests to the cursor are answered from this temporary table in tempdb; therefore, modifications made to base tables are not reflected in the data returned by fetches made to this cursor, and this cursor does not allow modifications. KEYSET Specifies that the membership and order of rows in the cursor are fixed when the cursor is opened. The set of keys that uniquely identify the rows is built into a table in tempdb known as the keyset. Changes to nonkey values in the base tables, either made by the cursor owner or committed by other users, are visible as the owner scrolls around the cursor. Inserts made by other users are not visible (inserts cannot be made through a Transact-SQL server cursor). If a row is deleted, an attempt to fetch the row returns an @@FETCH_STATUS of -2. Updates of key values from outside the cursor resemble a delete of the old row followed by an insert of the new row. The row with the new values is not visible, and attempts to fetch the row with the old values return an @@FETCH_STATUS of -2. The new values are visible if the update is done through the cursor by specifying the WHERE CURRENT OF clause. DYNAMIC Defines a cursor that reflects all data changes made to the rows in its result set as you scroll around the cursor. The data values, order, and membership of the rows can change on each fetch. The ABSOLUTE fetch option is not supported with dynamic cursors. FAST_FORWARD Specifies a FORWARD_ONLY, READ_ONLY cursor with performance optimizations enabled. FAST_FORWARD cannot be specified if SCROLL or FOR_UPDATE is also specified. FAST_FORWARD and FORWARD_ONLY are mutually exclusive, if one is specified the other cannot be specified. READ_ONLY Prevents updates from being made through this cursor. The cursor cannot be referenced in a WHERE CURRENT OF clause in an UPDATE or DELETE statement. This option overrides the default capability of a cursor to be updated. SCROLL_LOCKS Specifies that positioned updates or deletes made through the cursor are guaranteed to succeed. Microsoft SQL Server locks the rows as they are read into the cursor to ensure their availability for later modifications. SCROLL_LOCKS cannot be specified if FAST_FORWARD is also specified. OPTIMISTIC Specifies that positioned updates or deletes made through the cursor do not succeed if the row has been updated since it was read into the cursor. SQL Server does not lock rows as they are read into the cursor. It instead uses comparisons of timestamp column values, or a checksum value if the table has no timestamp column, to determine whether the row was modified after it was read into the cursor. If the row was modified, the attempted positioned update or delete fails. OPTIMISTIC cannot be specified if FAST_FORWARD is also specified. TYPE_WARNING Specifies that a warning message is sent to the client if the cursor is implicitly converted from the requested type to another.
_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 75

Bases de Dados II ISEP _________________________________________________________________________________________

select_statement Is a standard SELECT statement that defines the result set of the cursor. The keywords COMPUTE, COMPUTE BY, FOR BROWSE, and INTO are not allowed within select_statement of a cursor declaration. SQL Server implicitly converts the cursor to another type if clauses in select_statement conflict with the functionality of the requested cursor type. UPDATE [OF column_name [,...n]] Defines updatable columns within the cursor. If OF column_name [,...n] is supplied, only the columns listed allow modifications. If UPDATE is specified without a column list, all columns can be updated, unless the READ_ONLY concurrency option was specified.

_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 76

Bases de Dados II ISEP _________________________________________________________________________________________

6.1 Manipulao
O processo tpico da utilizao de um cursor : 1. Declarar variveis para guardar os valores retornados pelo cursor 2. Declarar um cursor com o comando Declare e associar-lhe um Select 3. Usar o comando Open para executar o Select e abrir o cursor 4. Utilizar instrues de posicionamento do cursor Fetch First Avana para o primeiro registo do cursor. Fetch Next Avana para o registo seguinte. Fetch Prior Avana para o registo anterior. Fetch Last Avana para o ltimo registo do cursor. Fetch Absolute n Avana para posio n do cursor. Fetch Relative n Avana n registos a partir do registo actual do cursor. @@Fetch_Status Permite testar o status do fetch, se diferente de zero, ocorreu um erro. NOTA : Para utilizar os comandos de fetch ( excepo do Next) necessrio declarar um cursor do tipo SCROLL. 5. Fechar o cursor com a instruo Close, para libertar a memria dos resultados do cursor, e possivelmente utilizar a instruo Deallocate se no for necessrio usar novamente o cursor.

_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 77

Bases de Dados II ISEP _________________________________________________________________________________________

Ex. Seleccionar todos os clientes atravs de um cursor DECLARE Cursor_Cli CURSOR FOR SELECT ClienteID, Nome FROM Clientes OPEN Cursor_Cli FETCH NEXT FROM Cursor_Cli WHILE @@FETCH_STATUS = 0 BEGIN FETCH NEXT FROM Cursor_Cli END CLOSE Cursor_Cli DEALLOCATE Cursor_Cli Ex. Seleccionar todos os clientes, seguido da descrio da sua posio de ordem (par ou mpar) no cursor

_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 78

Bases de Dados II ISEP _________________________________________________________________________________________

Ex. Estando os clientes todos ordenados alfabeticamente, imprima o primeiro, o terceiro e o ltimo.

_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 79

Bases de Dados II ISEP _________________________________________________________________________________________

7. Views
Uma view (vista) uma tabela virtual cuja estrutura e contedo definido atravs de uma query. A view criada dinamicamente a partir do momento que invocada. Uma view actua como um filtro sobre os dados da BD, e podem ser resultados de uma ou mais tabelas.

As views so normalmente utilizadas para simplificar a manipulao dos dados, e definir os dados na perspectiva do utilizador. Podem tambm ser utilizadas como mecanismos de segurana de dados, pois possvel definir seguranas ao nvel de uma view.

Syntax CREATE VIEW view_name [(column [,...n])] [WITH ENCRYPTION] AS select_statement [WITH CHECK OPTION] Arguments view_name Is the name of the view. View names must follow the rules for identifiers. Specifying the view owner name is optional.

_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 80

Bases de Dados II ISEP _________________________________________________________________________________________

column Is the name to be used for a column in a view. Naming a column in CREATE VIEW is necessary only when a column is derived from an arithmetic expression, a function, or a constant, when two or more columns may otherwise have the same name (usually because of a join), or when a column in a view is given a name different from that of the column from which it is derived. Column names can also be assigned in the SELECT statement. If column is not specified, the view columns acquire the same names as the columns in the SELECT statement. n Is a placeholder indicating that multiple columns can be specified. WITH ENCRYPTION Encrypts the syscomments entries that contain the text of the CREATE VIEW statement. AS Are the actions the view is to take. select_statement Is the SELECT statement that defines the view. It can use more than one table and other views. To select from the objects referenced in the SELECT clause of a view being created, it is necessary to have the appropriate permissions. A view does not have to be a simple subset of the rows and columns of one particular table. A view can be created using more than one table or other views with a SELECT clause of any complexity. There are, however, a few restrictions on the SELECT clauses in a view definition. A CREATE VIEW statement cannot: Include ORDER BY, COMPUTE, or COMPUTE BY clauses. Include the INTO keyword. Reference a temporary table. Because select_statement uses the SELECT statement, it is valid to use <join_hint> and <table_hint> hints as specified in the FROM clause. Functions can be used in the select_statement. select_statement can use multiple SELECT statements separated by UNION to create a query using partitioned data. For partitioned data to be used in ALTER VIEW or CREATE VIEW, constraint values must be able to be verified. If constraint checking has been disabled, reenable constraint checking with either the WITH CHECK option or the CHECK constraint_name options of ALTER TABLE. It is not necessary to have constraints to use partitioned data; however, query optimization generates less optimal plans without constraints. WITH CHECK OPTION Forces all data modification statements executed against the view to adhere to the criteria set within select_statement. When a row is modified through a view, the WITH CHECK OPTION guarantees that the data remains visible through the view after the modification has been committed.

_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 81

Bases de Dados II ISEP _________________________________________________________________________________________

Ex. CREATE VIEW vista_artigos AS SELECT ArtigoID, artigos.Descricao, familias.descricao AS DescFamilia FROM artigos, familias WHERE artigos.familiaID = familias.familiaID GO SELECT * FROM vista_artigos

Ex. ALTER VIEW vista_artigos AS SELECT ArtigoID, familias.descricao AS DescFamilia FROM artigos, familias WHERE artigos.familiaID = familias.familiaID Ex. DROP VIEW vista_artigos Ex. Criar uma view que contenha o nome do cliente e o volume bruto da sua facturao, desde que superior a 60000. Nome Volume ------------------------------------ --------------------Alexandre 71000.0000 Antnio 67000.0000

_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 82

Bases de Dados II ISEP _________________________________________________________________________________________

8. Stored Procedures
Stored Procedures so procedimentos semelhantes aos de outras linguagens, mas que podem ser guardados no servidor. Aceitam parmetros de entrada e retornam resultados Contm instrues que executam operaes na BD, incluindo chamadas a outras stored procedures Retornam um valor de status indicando se aconteceu um erro, e qual foi.

8.1 Vantagens
A utilizao de stored procedures trazem grandes vantagens, nomeadamente : Programao por mdulos Uma stored procedure aps ser guardada na BD, pode ser invocada vrias vezes no programa. Pode tambm ser alterada sem que haja necessidade de alterar em todos os lados. Execuo mais rpida Se uma operao tem muitas instrues T-SQL e/ou executada muitas vezes, as stored procedures conseguem ser mais rpidas, pois so compiladas e optimizadas no momento da sua criao. Diminuio do trfego na rede Uma operao T-SQL que contenha muitas linhas de cdigo pode ser executada atravs de uma nica linha de cdigo que enviado atravs da rede. Segurana Pode ser dada permisso aos utilizadores para executar uma stored procedure, mesmo que no tenham permisso para utilizar o mesmo cdigo directamente atravs de um editor.

_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 83

Bases de Dados II ISEP _________________________________________________________________________________________

8.2 Syntax
Ex. CREATE PROC Cli AS SELECT * FROM CLIENTE EXEC cli

Ex. ALTER PROC Cli @CodCli int AS SELECT * FROM CLIENTES WHERE ClienteID = @CodCli EXEC Cli 1

Syntax CREATE PROC[EDURE] procedure_name [;number] [ {@parameter data_type} [VARYING] [= default] [OUTPUT] ] [,...n] [WITH { RECOMPILE | ENCRYPTION | RECOMPILE, ENCRYPTION } ] [FOR REPLICATION] AS sql_statement [...n]

_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 84

Bases de Dados II ISEP _________________________________________________________________________________________

Arguments
procedure_name Is the name of the new stored procedure. Procedure names must conform to the rules for identifiers and must be unique within the database and its owner. Local or global temporary procedures can be created by preceding the procedure_name with a single number sign (#procedure_name) for local temporary procedures and a double number sign (##procedure_name) for global temporary procedures. The complete name, including # or ##, cannot exceed 128 characters. Specifying the procedure owner name is optional. ;number Is an optional integer used to group procedures of the same name so they can be dropped together with a single DROP PROCEDURE statement. For example, the procedures used with an application called orders may be named orderproc;1, orderproc;2, and so on. The statement DROP PROCEDURE orderproc drops the entire group. If the name contains delimited identifiers, the number should not be included as part of the identifier; use the appropriate delimiter around procedure_name only. @parameter Is a parameter in the procedure. One or more parameters can be declared in a CREATE PROCEDURE statement. The value of each declared parameter must be supplied by the user when the procedure is executed (unless a default for the parameter has been defined). A stored procedure can have a maximum of 1,024 parameters. Specify a parameter name using an at sign (@) as the first character. The parameter name must conform to the rules for identifiers. Parameters are local to the procedure; the same parameter names can be used in other procedures. By default, parameters can take the place only of constants; they cannot be used in place of table names, column names, or the names of other database objects. data_type Is the data type of the parameter. All data types, including text and image, can be used as a parameter for a stored procedure. However, the cursor data type can be used only on OUTPUT parameters. When you specify a data type of cursor, the VARYING and OUTPUT keywords must also be specified VARYING Specifies the result set supported as an output parameter (constructed dynamically by the stored procedure and whose contents can vary). Applies only to cursor parameters. default Is a default value for the parameter. If a default is defined, the procedure can be executed without specifying a value for that parameter. The default must be a constant or it can be NULL. It can include wildcard characters (%, _, [], and [^]) if the procedure uses the parameter with the LIKE keyword.

_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 85

Bases de Dados II ISEP _________________________________________________________________________________________

8.3 Parmetros
possvel passar parmetros para a uma stored procedure, que podem ser utilizados como variveis dentro da stored procedure. As stored procedures tambm podem retornar valores. Para cada parmetro necessrio definir o nome, o tipo de dados, a direco (entrada ou sada) e o valor defeito (opcional). Exemplo de parmetros de entrada ALTER PROC Cli @CodCli int=NULL, @InicioNome Varchar(40) AS SELECT * FROM CLIENTES WHERE ClienteID > @CodCli AND Nome LIKE (@InicioNome+'%') EXEC Cli 2, 'A' OU EXEC Cli @InicioNome = 'A', @CodCli=2

Exemplo de parmetros de sada ALTER PROC Cli @CodCli int, @InicioNome Varchar(40), @TotalReg int OUTPUT AS SELECT @TotalReg = COUNT(*) FROM CLIENTES WHERE ClienteID > @CodCli AND Nome LIKE (@InicioNome+'%') DECLARE @Tot int EXEC Cli 1, 'A', @TotalReg = @Tot OUTPUT PRINT 'Numero de registos = ' + cast(@Tot AS Varchar(10))

_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 86

Bases de Dados II ISEP _________________________________________________________________________________________

Exemplo de parmetro de resultado ALTER PROC Cli @CodCli int, @InicioNome Varchar(40), @TotalReg int OUTPUT AS BEGIN SELECT @TotalReg = COUNT(*) FROM CLIENTES WHERE ClienteID > @CodCli AND Nome LIKE (@InicioNome+'%') RETURN @@ERROR END DECLARE @Tot int, @Erro int EXEC @Erro = Cli 1, 'A', @TotalReg = @Tot OUTPUT IF @Erro <> 0 Print 'Ocorreu um erro !' ELSE PRINT 'Numero de registos = ' + cast(@Tot AS Varchar(10))

8.4 Exerccios
Ex. Criar uma stored procedure que mediante a entrada de 2 variveis (Cod e Nome) insira um registo no ficheiro de clientes e devolva um erro se acontecer algum problema.

_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 87

Bases de Dados II ISEP _________________________________________________________________________________________

Ex. Criar uma stored procedure que mediante a passagem dos parmetros descrio da famlia, data inicio e data fim, devolva a quantidade vendida dessa famlia nesse perodo.

Ex. Criar uma stored procedure que determine qual os dois cdigos de famlia de artigos com mais vendas, num determinado perodo. EXEC FamiliasMaisVendida '1991/01/01', '1999/01/01' FamiliaID Quantidade -------------- ----------1 17 5 6

_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 88

Bases de Dados II ISEP _________________________________________________________________________________________

Ex. Criar uma stored procedure que mediante a passagem de uma string, mostre todas as descries de artigos e todas as descries de famlias que tenham essa string, ordenadas. EXEC DescFamArt 'a' Descricao ---------------------------------------Cala ganga azul Cala ganga branca Cala ganga preta Calas

Ex. Criar uma stored procedure que devolva a mdia de descontos por factura. Mdia 1133.33

_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 89

Bases de Dados II ISEP _________________________________________________________________________________________

Ex. Criar uma stored procedure que devolva o primeiro e o terceiro desconto de factura, desde que acima da mdia de descontos das factura.
Primeiro 6000 Terceiro 5500

_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 90

Bases de Dados II ISEP _________________________________________________________________________________________

9. User Functions
Apesar das funes j existentes, possvel serem criadas outras que podem ser invocadas embutidas num query, ou atravs do comando EXECUTE (semelhante as Stored Procedures).

9.1 Utilizao
A utilizao de funes vantajosa em determinadas circunstancias : Podem ser utilizados para encapsular e centralizar a lgica das regras de negcio. Podem ser utilizadas numa query, contrariamente as Stored procedures e podem ser passados parametros, contrariamente as Views. Nos casos em que o resultado uma tabela, esta pode ser usado na clusula FROM como uma tabela normal. Nsa situaes em que o resultado um nico valor, as funces podem ser usadas na clusula SELECT como uma funo normal do SQL. Pode ser usada, por exemplo, para clculos de valores ou formatao.

9.2 Scalar Functions


So funes que retornam unicamente um valor. Ex. CREATE FUNCTION QtStock (@Qt Smallint) RETURNS Smallint AS BEGIN IF @QT<0 SET @Qt = 0 RETURN @Qt END Testar : SELECT dbo.QtStock(-3)

_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 91

Bases de Dados II ISEP _________________________________________________________________________________________

9.3 Inline Table-valued Functions


So funes que tm como resultado uma tabela de valores que resultado de uma nica instruo de select. Ex. Retornar todos os clientes que fazem anos num determinado ms. CREATE FUNCTION AnivMes (@Mes Tinyint) RETURNS TABLE AS RETURN (SELECT ClienteID, Nome FROM Clientes WHERE Month(DataNasc) = @Mes) Testar: SELECT Nome from AnivMes(1)

9.4 Multi-statement Table-valued Functions So funes que retornam tabelas definidas e trabalhadas pelo utilizador.
Ex. Retornar as vendas de artigos num determinado ano CREATE FUNCTION ArtVendasAno (@Ano Int) RETURNS @VAno TABLE (ArtigoID int, Descricao Nvarchar(40), Vendas Int) AS BEGIN INSERT @VAno SELECT ArtigoID, Descricao, (Select SUM(Quant) FROM Facts, linhasFact WHERE LinhasFact.ArtigoID = Artigos.ArtigoID AND LinhasFact.FactID = Facts.FactID AND @Ano = YEAR(Data)) FROM Artigos RETURN END
_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 92

Bases de Dados II ISEP _________________________________________________________________________________________

Testar com : SELECT * FROM ArtVendasAno(1998) WHERE Vendas > 1

9.5 Syntax
Scalar Functions CREATE FUNCTION [ owner_name. ] function_name ( [ { @parameter_name [AS] scalar_parameter_data_type [ = default ] } [ ,...n ] ] ) RETURNS scalar_return_data_type [ WITH < function_option> [ [,] ...n] ] [ AS ] BEGIN function_body RETURN scalar_expression END Inline Table-valued Functions CREATE FUNCTION [ owner_name. ] function_name ( [ { @parameter_name [AS] scalar_parameter_data_type [ = default ] } [ ,...n ] ] ) RETURNS TABLE [ WITH < function_option > [ [,] ...n ] ] [ AS ] RETURN [ ( ] select-stmt [ ) ] Multi-statement Table-valued Functions CREATE FUNCTION [ owner_name. ] function_name ( [ { @parameter_name [AS] scalar_parameter_data_type [ = default ] } [ ,...n ] ] ) RETURNS @return_variable TABLE < table_type_definition > [ WITH < function_option > [ [,] ...n ] ] [ AS ] BEGIN function_body RETURN END
_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 93

Bases de Dados II ISEP _________________________________________________________________________________________

< function_option > ::= { ENCRYPTION | SCHEMABINDING } < table_type_definition > :: = ( { column_definition | table_constraint } [ ,...n ] )

Arguments
owner_name Is the name of the user ID that owns the user-defined function. owner_name must be an existing user ID. function_name Is the name of the user-defined function. Function names must conform to the rules for identifiers and must be unique within the database and to its owner. @parameter_name Is a parameter in the user-defined function. One or more parameters can be declared in a CREATE FUNCTION statement. A function can have a maximum of 1,024 parameters. The value of each declared parameter must be supplied by the user when the function is executed, unless a default for the parameter is defined. When a parameter of the function has a default value, the keyword "default" must be specified when calling the function in order to get the default value. This behavior is different from parameters with default values in stored procedures in which omitting the parameter also implies the default value. Specify a parameter name using an at sign (@) as the first character. The parameter name must conform to the rules for identifiers. Parameters are local to the function; the same parameter names can be used in other functions. Parameters can take the place only of constants; they cannot be used in place of table names, column names, or the names of other database objects. scalar_parameter_data_type Is the parameter data type. All scalar data types, including bigint and sql_variant, can be used as a parameter for user-defined functions. The timestamp data type and user-defined data types not supported. Nonscalar types such as cursor and table cannot be specified. scalar_return_data_type Is the return value of a scalar user-defined function. scalar_return_data_type can be any of the scalar data types supported by SQL Server, except text, ntext, image, and timestamp. scalar_expression Specifies the scalar value that the scalar function returns. TABLE Specifies that the return value of the table-valued function is a table. In inline table-valued functions, the TABLE return value is defined through a single SELECT statement. Inline functions do not have associated return variables.
_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 94

Bases de Dados II ISEP _________________________________________________________________________________________

In multi-statement table-valued functions, @return_variable is a TABLE variable, used to store and accumulate the rows that should be returned as the value of the function. function_body Specifies that a series of Transact-SQL statements, which together do not produce a side effect, define the value of the function. function_body is used only in scalar functions and multi-statement table-valued functions. In scalar functions, function_body is a series of Transact-SQL statements that together evaluate to a scalar value. In multi-statement table-valued functions, function_body is a series of Transact-SQL statements that populate a table return variable. select-stmt Is the single SELECT statement that defines the return value of an inline table-valued function. ENCRYPTION Indicates that SQL Server encrypts the system table columns containing the text of the CREATE FUNCTION statement. Using ENCRYPTION prevents the function from being published as part of SQL Server replication. SCHEMABINDING Specifies that the function is bound to the database objects that it references. If a function is created with the SCHEMABINDING option, then the database objects that the function references cannot be altered (using the ALTER statement) or dropped (using a DROP statement).

_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 95

Bases de Dados II ISEP _________________________________________________________________________________________

9.6 Exerccios
Exerccio : Crie uma funo que devolva os dados do tipo DateTime no seguinte formato : Ano-Ms-Dia Soluo:

Exerccio : Crie uma funo que mediante a passagem de um determinado ano / ms, devolva todos os clientes que fazem anos nesse ms, seguido da sua idade relativamente ao ano passado como parmetro. Soluo:

_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 96

Bases de Dados II ISEP _________________________________________________________________________________________

10.Exerccios
10.1 Crie um Stored Procedure que liste as descries de todos os produtos que tm filhos. Soluo:

10.2 Criar um Stored Procedure que receba como parmetro o cdigo do produto e caso ele exista, retorne num parmetro a descrio do mesmo. Se o produto no existe dever retornar: 'Produto inexistente' Soluo:

_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 97

Bases de Dados II ISEP _________________________________________________________________________________________

10.3 Criar um Stored Procedure que liste as descries de todos os produtos que tm filhos soluo:

10.4 Criar um Stored Procedure que receba como parmetro o cdigo de um produto e retorne a estrutura da rvore correspondente

_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 98

Bases de Dados II ISEP _________________________________________________________________________________________

10.5. Criar um Stored Procedure que calcule os preos de compra de todos os produtos que tm filhos, sabendo que esse preo de compra o somatrio do preo de compra vezes a quantidade para cada um dos seus filhos. Soluo:

_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 99

Bases de Dados II ISEP _________________________________________________________________________________________

10.6. Criar um stored procedure que receba como parmetro um cdigo de produto e crie as ordens de fabrico necessrias para o produzir. Devero ser criadas ordens de fabrico para o produto e para cada um dos seus descendentes que tm filhos. Cada ordem de fabrico dever ter um n nico, quais os produtos necessrios para a produzir, respectivas quantidades, preo de compra de cada produto, preo de compra total e preo de venda. O preo de venda calculado como sendo o preo de compra + 10% + 1% por cada filho que o produto tiver.
Exemplo: up_ordemfabrico A, 1 Resultado:

Contedo da tabela OrdemFab: NumOrdem 1 2 3 Produto A C D Qtd 1 4 1 PrecoCompra 1740 380 20 PrecoVenda 1740 + 10%(1740) + 3%(1740) 380 + 10%(380) + 2%(380) 20 + 10%(20) + 1%(20)

_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 100

Bases de Dados II ISEP _________________________________________________________________________________________

Contedo da tabela OrdemFabDetalhe: NumOrdem 1 1 1 2 2 3 Filho B C D E F H Qtd 2 4 1 2 2 1 Preco 100 380 20 40 150 20

CREATE TABLE OrdemFab ( NumOrdem int NOT NULL identity(1, 1), ArtigoID varchar (10) NOT NULL, Qtd int NOT NULL DEFAULT 1 CHECK (Qtd > 0), PrecoCompra real NULL, PrecoVenda real NULL, CONSTRAINT PK_OrdemFab PRIMARY KEY NONCLUSTERED (NumOrdem), CONSTRAINT FK_OrdemFab1 FOREIGN KEY (ArtigoID) REFERENCES Artigos (ArtigoID)) CREATE TABLE OrdemFabDetalhe ( NumOrdem int NOT NULL, Filho varchar (10) NOT NULL , Qtd real NOT NULL DEFAULT 1 CHECK (Qtd > 0), Preco real NULL, CONSTRAINT PK_OrdemFabDetalhe PRIMARY KEY NONCLUSTERED (NumOrdem, Filho), CONSTRAINT FK_OrdemFabDetalhe1 FOREIGN KEY (Filho) REFERENCES artigos (artigoID), CONSTRAINT FK_OrdemFabDetalhe2 FOREIGN KEY (NumOrdem) REFERENCES OrdemFab (NumOrdem))

Soluo:
_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 101

Bases de Dados II ISEP _________________________________________________________________________________________

_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 102

Bases de Dados II ISEP _________________________________________________________________________________________

10.7. Criar um stored procedure que permita verificar se a estrutura da rvore vlida. A estrutura invlida se um produto tiver um ou mais filhos (em qualquer nvel da rvore) com o seu cdigo. Soluo:

_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 103

Bases de Dados II ISEP _________________________________________________________________________________________

11. Triggers
Um trigger uma stored procedure que automaticamente executada em resposta a um determinado evento. Esses eventos poder ser de Insert, Update ou Delete. Os triggers so tratados como transaes, ou seja, se acontecer um problema, desfeito tudo que esse trigger tivesse feito.

11.1 Utilizao
A utilizao de triggers vantajosa em determinadas circunstancias : Podem ser utilizados para efectuar alteraes em cascade, por exemplo, se apagar a factura eliminar automaticamente todas as linhas. Podem ser utilizados para colocar restries mais complexas que as definidas numa instruo de Check, pois podem utilizar validaes de colunas que tenham ligao com outras tabelas (ao contrrio do Check). O trigger tem a possibilidade de saber o estado do registo antes e depois de uma determinada alterao, e efectuar aces de acordo com esse estado. possvel executar um trigger diferente por cada evento de Insert, Update ou Delete. Ex. CREATE TRIGGER InsertClientes ON Clientes FOR INSERT AS PRINT 'Foi inserido um registo em clientes' Testar : INSERT INTO clientes (ClienteID, Nome) Values (99, 'Cliente 99')

Ex.
ALTER TRIGGER InsertClientes ON Clientes FOR INSERT AS PRINT 'Foi inserido um registo em clientes' Ex. DROP TRIGGER InsertClientes
_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 104

Bases de Dados II ISEP _________________________________________________________________________________________

11.1 Syntax
Syntax CREATE TRIGGER trigger_name ON table [WITH ENCRYPTION] { {FOR { [DELETE] [,] [INSERT] [,] [UPDATE] } [WITH APPEND] [NOT FOR REPLICATION] AS sql_statement [...n] } | {FOR { [INSERT] [,] [UPDATE] } [WITH APPEND] [NOT FOR REPLICATION] AS { IF UPDATE (column) [{AND | OR} UPDATE (column)] [...n] | IF (COLUMNS_UPDATED() {bitwise_operator} updated_bitmask) { comparison_operator} column_bitmask [...n] } sql_statement [ ...n] } }
Arguments trigger_name Is the name of the trigger. A trigger name must conform to the rules for identifiers and must be unique within the database. Specifying the trigger owner name is optional. table Is the table on which the trigger is executed; sometimes called the trigger table. Specifying the owner name of the table is optional. Views cannot be specified. WITH ENCRYPTION Encrypts the syscomments entries that contain the text of CREATE TRIGGER. { [DELETE] [,] [INSERT] [,] [UPDATE] } | { [INSERT] [,] [UPDATE]} Are keywords that specify which data modification statements, when attempted against this table, activate the trigger. At least one option must be specified. Any combination of these in any order is allowed in the trigger definition. If more than one option is specified, separate the options with commas.
_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 105

Bases de Dados II ISEP _________________________________________________________________________________________

WITH APPEND Specifies that an additional trigger of an existing type should be added. Use of this optional clause is needed only when the compatibility level is less than or equal to 65. If the compatibility level is greater than or equal to 70, the WITH APPEND optional clause is not needed to add an additional trigger of an existing type (this is the default behavior of CREATE TRIGGER with the compatibility level setting greater than or equal to 70.) . NOT FOR REPLICATION Indicates that the trigger should not be executed when a replication process modifies the table involved in the trigger. AS Are the actions the trigger is to take. sql_statement Is the trigger condition(s) and action(s). Trigger conditions specify additional criteria that determine whether the attempted DELETE, INSERT, or UPDATE statements cause the trigger action(s) to be carried out. The trigger actions specified in the Transact-SQL statements go into effect when the user action (DELETE, INSERT, or UPDATE) is attempted. Triggers can include any number and kind of Transact-SQL statements except SELECT. A trigger is designed to check or change data based on a data modification statement; it should not return data to the user. The Transact-SQL statements in a trigger often include control-of-flow language. A few special tables are used in CREATE TRIGGER statements: deleted and inserted are logical (conceptual) tables. They are structurally similar to the table on which the trigger is defined (that is, the table on which the user action is attempted) and hold the old values or new values of the rows that may be changed by the user action. For example, to retrieve all values in the deleted table, use: SELECT * FROM deleted n Is a placeholder indicating that multiple Transact-SQL statements can be included in the trigger. For the IF UPDATE (column) statement, multiple columns can be included by repeating the UPDATE (column) clause. IF UPDATE (column) Tests for an INSERT or UPDATE action to a specified column and is not used with DELETE operations. More than one column can be specified. Because the table name is specified in the ON clause, do not include the table name before the column name in an IF UPDATE clause. To test for an INSERT or UPDATE action for more than one column, specify a separate UPDATE(column) clause following the first one. UPDATE(column) can be used anywhere inside the body of the trigger. column Is the name of the column to test for either an INSERT or UPDATE action. This column can be of any data type supported by SQL Server.

_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 106

Bases de Dados II ISEP _________________________________________________________________________________________

IF (COLUMNS_UPDATED()) Tests, in an INSERT or UPDATE trigger only, whether the mentioned column or columns were inserted or updated. COLUMNS_UPDATED returns a varbinary bit pattern that indicates which columns in the table were inserted or updated. COLUMNS_UPDATED can be used anywhere inside the body of the trigger. bitwise_operator Is the bitwise operator to use in the comparison. updated_bitmask Is the integer bitmask of those columns actually updated or inserted. For example, table t1 contains columns C1, C2, C3, C4, and C5. To check whether columns C2, C3, and C4 are all updated (with table t1 having an UPDATE trigger), specify a value of 14. To check whether only column C2 is updated, specify a value of 2. comparison_operator Is the comparison operator. Use the equals sign (=) to check whether all columns specified in updated_bitmask are actually updated. Use the greater than symbol (>) to check whether any or some of the columns specified in updated_bitmask are updated. column_bitmask Is the integer bitmask of those columns to check whether they are updated or inserted.

Ex. ALTER TRIGGER UpdateClientes ON Clientes FOR UPDATE AS BEGIN DECLARE @OldNome Varchar(40), @NewNome Varchar(40) SELECT @OldNome=Nome FROM deleted SELECT @NewNome=Nome FROM inserted PRINT 'O nome do cliente foi alterado de ' + @OldNome + ' para ' + @NewNome END UPDATE Clientes SET Nome = 'Osrio' WHERE ClienteID = 99

_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 107

Bases de Dados II ISEP _________________________________________________________________________________________

11.2 Exerccios Ex. Criar um trigger que actualize automaticamente a existncia do artigo sempre que seja inserida uma linha de factura.

Ex. Criar um trigger que actualize automaticamente a existncia do artigo sempre que seja apagada uma linha de factura.

_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 108

Bases de Dados II ISEP _________________________________________________________________________________________

Ex. Criar um trigger que actualize automaticamente a existncia do artigo sempre que seja alterada uma linha de factura.

_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 109

Bases de Dados II ISEP _________________________________________________________________________________________

Ex. Criar um trigger que no deixe criar clientes da zona Norte.

_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 110

Bases de Dados II ISEP _________________________________________________________________________________________

12. Exerccios Gerais


12.1 Escreva um script que imprima os dois artigos mais vendidos por zona, no seguinte formato : Zona Artigo Quantidade --------- ---------- -------------1 4 10 1 5 <- Linha em branco na quebra 2 3 5 2 4 5 <- Linha em branco na quebra 5 1

_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 111

Bases de Dados II ISEP _________________________________________________________________________________________

_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 112

Bases de Dados II ISEP _________________________________________________________________________________________

12.2 Escreva uma stored procedure que mediante a passagem de uma famlia, diga em que zona(s) que aquela famlia no tem vendas. A famlia 3 tem vendas em todas as zonas OU A famlia 3 no tem vendas nas seguintes zonas : Norte Centro Sul

_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 113

Bases de Dados II ISEP _________________________________________________________________________________________

12.3 Criar uma view com as facturas j vencidas e com o nome do respectivo cliente. Nome FactID ClienteID Data DataVenc -------------------- ----------- --------------- ----------------- ----------------Antnio 1 1 1998-01-01 1998-01-01 Antnio 2 1 1998-02-01 1998-03-01 Afonso 3 2 1995-02-01 1995-04-01

12.4 Criar um trigger que avise quando um determinado artigo atinja a existncia inferior a 10.

_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 114

Bases de Dados II ISEP _________________________________________________________________________________________

12.5 Criar uma stored procedure que mediante a passagem de um ms, imprima etiquetas para envelopes, para todos os clientes que fazem anos nesse ms, desde que tenham alguma factura. Antnio Rua Afonso 437 Amial 4200 Porto

_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 115

Bases de Dados II ISEP _________________________________________________________________________________________

Bibliografia SQL Server Books Online www.microsoft.com/sql Seminrios Microsoft

_________________________________________________________________________________________ Antnio Rocha / Nuno Castro / Nuno Ferreira SQL Server (verso 3.01) Pg 116