Sie sind auf Seite 1von 12

Introduction to SQL

SQL (Structured Query Language) is a standard language used to access the databa
se. All of your commands allows us to define the structure of data in relational
database, access and manipulate data. This is not a Procedural Language. When u
sing SQL, we specify what we do, not how to do it. It is a language easy to lear
n. SQL began in 1970, EF Codd, who formulated the principles of a system for man
ipulating relational database, and described a relational algebra to organize da
ta in tables. Since then, the language was improved and now there is a standard
developed by the American National Standards Institute (ANSI). This pattern has
been the basis for most SQL's currently on the market. Each manufacturer has ins
erted new features in your SQL, so we can find dozens of versions of SQL. We pre
sent below an overview of the architecture of a System Manager Database, so we c
an understand what it composes the SQL language.
DBMS Architecture
External view 1
Vision foreign n
External Level
Conceptual Schema
Conceptual Level
Internal Schema
Internal Level
Database
1
1) Level Procedure. Describes the physical structure of database storage. Intern
al Schema uses a physical data model and describes all the details of data stora
ge and access paths to the database. 2) Conceptual Level. Describes the structur
e of the entire database for users. The Conceptual Schema hides the details of t
he physical structure of storage and concentrates on describing entities, data t
ypes, relationships, user operations and restrictions. 3) External Degree. Inclu
des a number of external schemas or user views. Each one describes a part of the
database that a particular group of users are interested in and hides the rest
of the database to other users.
DBMS Languages
Data Definition Language (DDL) - To define the conceptual schema and internal sc
hema. View Definition Language (VDL) - To set the views of users and their mappi
ngs to the conceptual schema. Data Manipulation Language (DML) - To handle the d
ata in a database. (Read, Insert, Delete, Edit).
SQL = (DDL + VDL + DML)
Data Definition in SQL
SQL uses the terms table (table), row (row) and column (column) for relationship
or entity, tuple and attribute, respectively. The Data Definition Language (DDL
), enables you to perform tasks like: - create an object database - delete an ob
ject database - change an object database - grant privileges on an object databa
se - revoke privileges on an object database
2
Concepts used in SQL
We present some objects and concepts in the understanding of SQL. Database (Data
base). It is a set of SQL objects. When we define a database, we will give you a
name for an eventual collection of tables and associated indexes. Table. A data
base contains one or more tables. Each table has a name and contains a specific
number of columns and rows (not ordered). Index. It is an ordered set of pointer
s to the data from a table, stored separately in the table. Each index is based
on the data values of one or more columns in a table. The index aims to improve
the performance and also ensure the uniqueness of the data (if desired). Vision
(View). It is an alternative way to represent data that exists in one or more ta
bles. A view may have some or all columns of one or more tables. You can also ha
ve views based on other views or combination of views and tables. It resembles a
table, with the only difference, that view does not exist physically. Your data
is stored in tables in which they are based. Join (Join). When you want to get
data from more than one table, we made the junction of these tables. Primary Key
(Primary Key). It is a Columa or group of columns whose value identifies each t
able row. Foreign Key (Foreign Key). Columns of tables that reference the primar
y key in another table. Referential Integrity. When we define a foreign key, we
are defining a referential integrity between the tables involved. Catalog System
. Each database has a system catalog that contains the system tables. These tabl
es contain information about tables, views, columns, indexes, and security privi
leges of the database. In some DBMSs, this catalog is called the data dictionary
.
-
-
-
-
-
-
-
-
3
Data Types (Datatypes)
Data types specify what kind of information (characters, numbers, dates) column
of a table can hold and how this data will be stored.€Discuss below some data ty
pes found in Microsoft's SQL. Binary [(n)] Varbinary [(n)] char [(n)] Varchar [(
n)] Datetime smalldatetime decimal [(p [, s])] Numeric [(p [, s])] tinyint Small
int Int Money Text Image Smallmoney Bit, timestamp Qty fixed binary numbers Qty
variable binary numbers (most economical) Qty Qty fixed character variable chara
cters (most economical) Date of accurately HHMMSS, MS (fuller) Date with an accu
racy of numerical values HHMMSS , where p is the total qty including the integer
part and decimal part represents the decimal part eos Integers. (-255 To +255)
Númerso integers. (-32,767 To +32,767) Integers. Monetary value Monetary values
Texts Photos and Images Special data types
You can create your data type and store it in the database to use it in defining
the columns of the new tables. Examples: EXEC sp_addtype cep, 'char (10)' EXEC
sp_addtype grandestring 'varchar (75)' EXEC sp_droptype cep
4
Creating Tables
To create tables within a database, use the CREATE TABLE sentence. CREATE TABLE
[database_name. [Dono_tabela]. ] Table_name ([col_name propriedades_col [constra
int [constraint [... constraint]]] | [[,] constraint]] [[,] [próximo_nome_col |
próxima_constraint] ...]) • • • • •
Column names must be unique within a table Every column must have a data type (d
atatype) You can define up to 2 billion tables per database You can define up to
250 columns per table A NULL value indicates no data. NULL is not white and not
zero. By default, SQL assumes NOT NULL for columns that are not declared as nul
l. You can change this default configuration of SQL Server.
Examples: CREATE TABLE company (CGC cod_empresa yourcompany dt_fundacao nro_func
ionarios
int NOT NULL, varchar (45) NOT NULL, char (14) NOT NULL, smalldatetime, smallint
)
CREATE TABLE employee (cod_func int, nome_func varchar (45), address varchar (50
) city varchar (30)
NULL, NULL)
5
Referential Integrity, Primary Key and Foreign Key
Referential Integrity in a Relational Database is the finding that the links bet
ween the rows of related tables are valid. These links are implemented in the re
lationship between the primary key (PK) of a table with the foreign key (FK) fro
m the same table (in case of a self-relationships) or from another table. We cal
l the table containing the primary key of parent table, and that contains the fo
reign key in child table. When we create a relationship of Father and Son using
the Primary Key and Foreign Key, the DBMS automatically begins to check the refe
rential integrity of the rows of tables involved, thus eliminating the need for
such checks in the programming of applications. As an example, let's consider an
application that deals with requests from a client. We have a Customer table th
at is the parent table from another table application, where the primary key of
the table Customer is código_do_cliente. When we created the link between the tw
o tables, we have a column in the table código_do_cliente Request to be appointe
d to the Foreign Key Primary Key of the table Customer. Thus when the applicatio
n is to insert a request from a client application on the table, the DBMS will c
heck if that customer already exists in the Customer table, returning an error i
f does not meet this condition.
Customer Cód_cliente (PK) customer_name CGC Address
Request Cód_cliente (PK) / (FK) Nro_pedido (PK) Data_pedido
6
CREATE TABLE customer (CGC cod_cliente customer_name Address
int Primary Key, varchar (30), varchar (14), varchar (50))
CREATE TABLE request (cod_cliente int, int nro_pedido, data_pedido smalldatetime
, pk_pedido CONSTRAINT PRIMARY KEY (cod_cliente, nro_pedido) fk_cliente_pedido C
ONSTRAINT FOREIGN KEY (cod_cliente) REFERENCES customer (cod_cliente))
Amendment of Tables
ALTER TABLE table_name ((CHECK | NOCHECK) CONSTRAINT (nome_constraint | ALL) | [
(ADD col_name propriedades_col [constraints_col] | [[,] constraint_tabela]) [(pr
oxima_col | proxima_constraint_tabela)] ... ] | [DROP CONSTRAINT] nome_constrain
t [, nome_constraint2] ... ]
• • •
You can enable and disable of Foreign Key constraints and check with the CHECK o
ption (enables) and NOCHECK (disable). The column to be added to the table (ADD)
should be set to NULL. You can add a new constraint to the table or delete an e
xisting one.
7
Examples
ALTER TABLE dept ADD nome_chefia
varchar (20)
NULL
ALTER TABLE employee NOCHECK fk_depto_emp CONSTRAINT ALTER TABLE employee ADD CO
NSTRAINT FOREIGN KEY fk_depto_emp (cod_depto) REFERENCES dept (cod_depto) ALTER
TABLE employee DROP CONSTRAINT fk_depto_emp
Deleting Tables
DROP TABLE table_name
• •
You can not delete a table if it has some other table "daughter" attached to it.
When you delete a table, all records contained therein are deleted and the tabl
e itself with all its structure is deleted from the database.
Example:
DROP TABLE employee
8
Extracting Information in Tables
In order to be able to query the data stored in tables, use the SELECT command.
SELECT [ALL | DISTINCT] select_list FROM tbl_name [, tbl_name2] [..., nome_tabel
a16] [WHERE clause] [GROUP BY clause] [HAVING clause] [ORDER BY clause] [COMPUTE
clause]
• • • • •
SELECT - specifies the columns FROM - specifies the tables
WHERE - specifies the rows * When using the select list, we select all columns o
f the table. Not using the WHERE clause, all rows are selected.
Examples SELECT * FROM Employee SELECT name, age, salary FROM employee SELECT co
d_depto, cod_empregado, salary FROM employee WHERE salary> 1200
9
Using Literals
SELECT name, 'Code of Department:' cod_depto FROM dept
Setting Column Header
By default, the header shown in the result of a query is the name of the column
defined in table creation. However, it is possible to change this header, insert
ing it into the list of Select.
NOME_EMPREGADO = SELECT name FROM employee hire_date = dt_admissao
Arithmetic Operators
Arithmetic operators can be used on any numeric column (numeric, decimal, int, s
mallint, tinynt, float, real, money or smallmoney). Symbol + / *% • Operation Ad
dition Subtraction Multiplication Division Module
The modulus operator (%) can not run on the data types money, smallmoney, float
or real.
SELECT name, salary, (salary * 1.15) FROM employee
10
Functions of Numerical Data Handling:
ABS function CEILING EXP FLOOR LOG LOG10 PI SQRT ROUND SIGN Parameter (numeric_e
xpr) (numeric_expr) (float_expr) (numeric_expr) (float_expr) (float_expr) () (nu
meric_expr, lenght) (float_expr) (numeric_expr) Income Absolute Value Greater ne
arest whole or equal to the specified value value value specified exponential Mi
nor nearest integer or equal to the logarithm of the numeric value specified spe
cified logarithm base 10 value of constant size specified 3.141592653589793 Roun
ding Square Root Positive, Negative or Zero
Data Manipulation Functions Character:
Function Result + Concatenate two or more character, strings or columns LOWER (c
har_expr) Converts to lowercase LTRIM (char_expr) Deletion of the blanks left PA
TINDEX ('% string%', expression) Returns the first position of first occurrence
of string in expression defined, or zero if the string is not found REPLICATE (c
har_expr, integer_expr) Repeats a character expression as many times as specifie
d REVERSE (char_expr) Returns the inverse of char_expr. RIGHT (char_expr, intege
r_expr) part of the string starting integer_expr characteres right RTRIM (char_e
xpr) Removal of whitespace right SOUNDEX (char_expr) Returns a code of phonetic
similarities SPACE (integer_expr) Returns a string of repeated spaces SUBSTRING
(expression, start , length) Returns part of a string of characters. UPPER (char
_expr) Converts to uppercase James observed: combinations can be used for exampl
e: lower (field1 + field2) parameter (expression, expression)
11
Function Handling Dates:
Function DATEADD DATEDIFF DATENAME GETDATE Parameters (DatePart, number, date) (
DatePart, date1, date2) (DatePart, date) () Sum the number of results to date da
teparts Number dateparts between two dates Specifies DatePart to date, returning
as a ASCII value (eg September) Current date and time in internal format
DatePart Year Quarter Month Day of year Day Week weekday hour minute second mill
isecond
Abbreviation qq yy mm dd dy wk dw hh mi ss ms
Value 1753 - 9999 1-4 1-12 1-366 1-31 0-51 1-7 (1 is Sunday) 0-23 0-59 0-59 0-99
9
SELECT name, dt_admissao, DATEDIFF (month, dt_admissao, GETDATE ()) FROM Employe
e SELECT name FROM employee WHERE dt_admissao DATENAME (dw, dt_admissao) = "MOND
AY"
System Functions
Function col_name COL_LENGTH dataLength db_id DB_NAME HOST_NAME USER_ID USER_NAM
E parameters ('table_name', column_id) ('table_name', 'column_name') ('expressio
n') ('databasename') (database_id) () ('username') (user_id) Results Returns Ret
urns the column name column size Returns the current size of an expression of an
y type of data bank ID Returns Returns Returns database name computer name user
ID Returns Returns user name
12
SELECT size = dataLength (name), name FROM employee
DATA CONVERSION
The CONVERT function converts expressions from one data type to another type. It
also allows formatting dates in different styles.
CONVERT (data_type [(length)], expression [, style])
Style (yy) Style (yyyy) or 100 0 1101 2102 3103 4104 5105 6106 7107 8108 9 or 10
9 10 110 11 111 12 112 13 or 113 14 114
Default ANSI standard USA English / French German Italian Japanese USA milisegs
Default + ISO + European Default milisegs -
Date format month dd yyyy hh: mi AM (or PM) mm / dd / yy yy.mm.dd dd / mm / yy D
D.MM.YY dd-mm-dd month yy yy dd months. yy hh: mi: ss months dd.yyyy hh: mi: ss:
ms AM (or PM) mm-dd-yy yy / mm / dd months yymmdd dd yyyy hh: mi: ss: ms (24) h
h: mi: ss: ms (24h)
SELECT CONVERT (char (30), GETDATE (), 102) Result: 07/03/1999
13
Search Terms
Comparison Operators String Comparison Ranges Playlists Values unknown combinati
ons Negation Negative Operators Operator <> not column_name = column_name not> N
ot Between not like is not in not null meaning different than the column of no m
ore than between two non-existent values reported in a given list values than th
e default character informed is not a null value (=,>,<,>=,<=,<>,!=,!<,!>) (BETW
EEN and NOT BETWEEN) (IN and NOT IN) (LIKE and NOT LIKE) (IS NULL and IS NOT NUL
L) (AND, OR) (NOT)
Note: Avoid the use of conditions of Denial, as NOT IN and NOT BETWEEN, because
these conditions are not recognized by the query optimizer.
SELECT name FROM employee WHERE dt_admissao dt_admissao BETWEEN '1 / 1 / 95 'AND
'12 / 31/95' SELECT name FROM employee WHERE cod_depto cod_depto IN (1, 3, 4) S
ELECT * FROM employee WHERE name LIKE '% Jose % 'SELECT name FROM employee WHERE
salary IS NULL
14
SELECT * FROM employee WHERE (name LIKE 'S%' OR cod_depto = 1) AND (salary> 500.
00)
Eliminating duplicates:
SELECT DISTINCT name FROM employee
Sorting the result:
• • • You can set the ORDER BY clause on the number of column instead of column
name. By default, the ascending (ASC) is assumed. You can sort by up to 16 colum
ns.
SELECT name, cod_depto, salary FROM employee ORDER BY cod_depto, salary DESC
15
Aggregate Functions:
• • • Returns values summarized the result appears as new columns Used in the Se
lect List or in the HAVING clause returns the arithmetic mean of a column Return
s the total number of elements of the group returns the sum of a column Returns
the smallest value of a column Returns higher value of a column
COUNT SUM AVG MIN MAX
SELECT COUNT (*) FROM Employee SELECT SUM (salary) FROM Employee SELECT AVG (age
) FROM Employee SELECT MAX (salary) FROM employee
GROUP BY clause:
• • • Organizes data into groups, usually used with aggregate functions follows
a single value for each group
16

Each column in the SELECT list must be in the GROUP BY clause
HAVING clause:
• • • • • Clause restriction group allows aggregate functions Similar to WHERE c
lause columns in the HAVING clause should have only a single query with HAVING A
value must have a GROUP BY
SELECT cod_depto, media_de_salario = AVG (salary) FROM employee GROUP BY SELECT
cod_depto cod_depto, salario_do_depto = SUM (salary) FROM employee GROUP BY cod_
depto HAVING SUM (salary)> 5000.00
COMPUTE and COMPUTE BY
• • • • • For use with aggregate functions of the computer generates a Grand Tot
al, while the COMPUTE BY generates Totals Groups This result generated, produces
a new line in the query result. You can get them by Group Totals and Grand Tota
l in the same query is not standard ANSI
Cod_depto SELECT name, salary FROM employee WHERE salary> 500 COMPUTE SUM (salar
y) cod_depto SELECT name, salary FROM employee ORDER BY cod_depto
17
COMPUTE SUM (Salary) BY cod_depto COMPUTE SUM (Salary)
Restrictions: • • • You can not use DISTINCT with groupings should be used, ORDE
R BY, the COMPUTE BY is used The columns listed in the COMPUTE BY must be identi
cal or a subset of the columns listed in the ORDER BY.
JOINS: • • Operation that allows processing of two or more tables Implemented by
using the SELECT statement, where in the select list put the columns of one or
more tables that wish list, the FROM clause defined all the tables involved in t
he Join, and in the WHERE clause we specify which line will be included in the r
esult. In the WHERE clause, an operator join is used between the components that
are making the joint. You can set up 16 tables in the FROM clause. Typically, a
primary key is compared to a foreign key in any join operator is used to join t
he equal sign (=), which results only in rows where the column value from a tabl
e is equal to the value of another column table. If not set any condition of Joi
n (WHERE clause), it generates a Cartesian product between the tables. (Join Unr
estricted)
• • • •
Example Join Unrestricted (Cartesian product between tables):
SELECT nome_empreg, nom_depend FROM employee, dependent
In the above example, assuming that the Employee table has 10 rows, and Table 20
Dependent lines, then the result will be Unrestricted Join the 10 * 20 = 200 li
nes.
18
EQUI JOIN
• Specifies a condition of equality between the tables to meet the Join.
SELECT d.nome, e.nome FROM dept d, and employee WHERE d.cod_depto = SELECT e.cod
_depto d.nome, e.nome, dp.nome, dp.idade FROM dept d, employee and dependent dp
WHERE d. cod_depto = e.cod_depto AND e.cod_empreg = dp.cod_empreg
SELF JOIN
• • Perform the join lines in a table with other rows of same table Why treat th
e same table, you must define different aliases for these tables SELECT au1.au_f
name, au1.au_lname, au2.au_fname, au2.au_lname FROM authors au1 , authors WHERE
au1.city U2 = 'Oakland' AND au1.state = 'CA' AND au1.zip = au2.zip AND au1.au_id
<au2.au_id
OUTER JOIN
• • Displays all rows of the join, including those which have no corresponding r
ows in the related table. One can only do an outer join between two tables.
Outer Join operator: *= Includes all rows from the first table specified in the
constraints of the sentence =* Includes all rows from the second table specified
in the constraints of the sentence SELECT titles.title_id, title, qty FROM titl
es, sales
19
WHERE titles.title_id *= sales.title_id
Subqueries:
• • • • • Many nested SELECT statements are SQL statements that include subqueri
es may be formulated in an alternative way by Joins. Other queries are resolved
only with subqueries. The award of a SELECT subquery is always placed within par
entheses. A subquery can be inserted in the SELECT list, WHERE or HAVING clause
in the outer query. In normal nesting subqueries, the innermost are executed fir
st.
SELECT cod_depto, name FROM dept WHERE cod_depto IN (SELECT DISTINCT cod_depto F
ROM employee)
SELECT title = title_id, qty = Quantity, Total = (SELECT SUM (qty) FROM sales),
Porcentagem_do_Total = (CONVERT (float, qty) / (SELECT SUM (qty) FROM sales)) *
100 FROM sales
Subqueries RELATED:
20

Subqueries are those that reference in the WHERE clause, a table of the FROM cla
use of the outer query. In this case, the subquery is executed for each row of t
he table referenced in the outer query.
SELECT title_id, au_id, royaltyper titleauthor FROM ta WHERE royaltyper = (SELEC
T MAX (royaltyper) FROM tb WHERE titleauthor tb.title_id = ta.title_id)
SELECT INTO
• • • • Creates a new table based on the result of a SELECT If the new table is
a permanent table, the option select into / bulkcopy should be reported in the d
atabase configuration. If the new table is a temporary table, the name of this s
hould be preceded by a # or # # The columns in the select list must have aliases
(alias) Denotes new to the table as being temporary, putting a sign in scope (#
) as first character of the table name.
Phnom = SELECT SUBSTRING (name, 1, 10), Sal_anual salary = 12 * INTO # novatabel
a FROM employee
• Allows UNION operator to merge the results of two or more queries into a singl
e result.
• The increase results in a UNION of rows. (A JOIN results in an increase of col
umns).
21
• • • •
In marriage, the structures of the columns must be the same, and compatible data
types. By default, duplicate rows are removed from the final result. If you wan
t them to stay, use the ALL option. The lists of speakers should Selects Having
the same number of columns, data types, similar, and appear in the same order. T
he column names are taken from the first SELECT statement.
Lista_de_select SELECT FROM ... UNION [ALL] SELECT ... FROM lista_de_select
Inserting LINES:
• • • • The INSERT command is used to add rows to a table using an INSERT statem
ent for each row to be added to the order and data type of item to be inserted m
ust match the order and type as the columns of the table items Data in the VALUE
S clause must match the list of column names
INSERT [INTO] (table_name | nome_view) [(lista_de_colunas)] (VALUES (lista_de_va
lores) | sentença_select)
INSERT INTO dept VALUES (1, 'ACCOUNTING') INSERT INTO employee (nro_empregado na
me, cod_depto) VALUES (7000, 'Jose Luiz de Oliveira', 1)
22
Inserting Rows with SELECT
• Insert rows resulting from a query on a table that already exists. INSERT INTO
table_name SELECT lista_de_colunas lista_de_tabelas FROM [WHERE condições_de_pe
squisa]
INSERT INTO SELECT empreg_salarioanual nome_empreg, (salary * 12) FROM employee
WHERE age> 21
Changing Line data:
• • • • The UPDATE command changes the data rows from a table The SET clause spe
cifies the column and value to change the WHERE clause identifies the exact rows
to be changed if the UPDATE violates some integrity constraint, the change will
not run
UPDATE (table_name | nome_view SET column_name = expression) [, column_name = ex
pression, ... ] [WHERE clause]
UPDATE employee SET salary = salary * 1:05 UPDATE employee SET WHERE cod_depto c
od_depto = 5 = 2
23
Change based on data from other tables:
UPDATE titles ytd_sales SET = (SELECT SUM (qty) FROM sales WHERE sales.title_id
= titles.title_id ORD_DATE AND BETWEEN '01 / 01/95 'AND '12 / 31/95')
Deleting Rows:
• • • The DELETE command removes one or more rows from a table A WHERE clause sp
ecifies the criteria by which rows will be removed if the WHERE clause is not sp
ecified, all table rows will be removed. DELETE [FROM] table_name [WHERE condiçõ
es_de_pesquisa]
DELETE employee WHERE DATEDIFF (YEAR, dt_admissao, GETDATE ())> = 5
The following two examples accomplish the same thing. Delete all rows from the t
able titleauthor that has the book title string "computers". / * Subquery ANSI *
/ DELETE FROM titleauthor WHERE au_id IN (SELECT a.au_id
24
FROM authors a, titles t WHERE ta titleauthor a.au_id = ta.au_id AND ta.title_id
= t.title_id t.title AND LIKE '% computers%') / * Transact-SQL extension * / DE
LETE FROM FROM titleauthor the authors , titles t WHERE AND t.title_id titleauth
or.au_id a.au_id = = titleauthor.title_id t.title AND LIKE '% computers%'
INDEXES:
• • • • • • • The main objective of using indexes is to increase the research pe
rformane Improves performance in the resolution of ORDER BY and GROUP BY The ban
k itself creates an index for each primary key defined in the table the changes
(UPDATE ) tend to become more time consuming when using indexes Avoid defining i
ndexes for columns of type text, image or bit Avoid defining indexes when the UP
DATE performance is more important than the performance of SELECT A UNIQUE claus
e specifies that the column or set of columns that comprise the index can not ha
ve duplicate values in the table.
CREATE UNIQUE INDEX ON i1_empregado employee (name)
Types of Indexes:
Not clustered Clustered
25
Clustered index:
• • • • • • • Lines are classified and sorted remains can only be one clustered
index per table The clustered index should always be the first index to be creat
ed. Great advantage when one wants to see huge gaps. Not defining the index is c
lustered, you create a clustered index does not.
Non-clustered indexes:
Physical classification of the lines is not the same classification indices. You
can have up to 249 non-clustered indexes per table. Each can provide access to
data in different orders.
CREATE CLUSTERED INDEX ON idc_empregado employee (name)
DATA INTEGRITY
The Data Integrity speaks of the consistency of data stored in a database, makin
g it easier for applications that make use of it. Property IDENTITY • • • • The
values for IDENTITY columns are defined as system-generated sequentially. Allowe
d only a single IDENTITY column per table can not be changed by an UPDATE comman
d Defined only for data types: tinyint, smallint, int, numeric, decimal
IDENTITY [(valor_inicial, increment)]
CREATE TABLE student (aluno_id INT IDENTITY (100, 5), name VARCHAR (20)) INSERT
student VALUES ('Mirtes') INSERT student VALUES ('Wagner') / / will be created w
ith aluno_id = 100 / / will be created with aluno_id = 105
26
DEFAULTS
• • • • • Created before or after the creation of table names must be unique wit
hin the Bank are checked to INSERT the data type must be the same as defined for
the associated table column must be compatible with the rules (rules) defined f
or column
CREATE DEFAULT def_uf AS 'SP'
RULES (RULES)
• • • • Created before or after the creation of table names must be unique withi
n the Bank are checked in INSERT and UPDATE Parameter name must be prefixed with
@
CREATE RULE AS rl_desconto @ desc = @ desc 10 OR <5
Both DEFAULTS as the RULES should be associated (linked) to a table column. EXEC
sp_bindefault def_uf, 'empregado.uf' EXEC sp_bindrule rl_desconto, 'duplicata.d
esc'
EXEC sp_unbindefault 'empregado.uf' EXEC sp_unbindrule 'duplicata.desc'
27
DROP DEFAULT DROP RULE def_uf rl_desconto
CONSTRAINTS
• • • Can be placed in a column or a table can be added to a table that already
contains data If you do not put a name for the constraint, the system creates a
standard with its
Types of Constraints: PRIMARY KEY DEFAULT CHECK UNIQUE FOREIGN KEY
ALTER TABLE employee ADD CONSTRAINT FOREIGN KEY fk_cod_depto (cod_depto) REFEREN
CES dept (cod_depto)
ALTER TABLE employee ADD CONSTRAINT UNIQUE uq_nome Nonclustered (name) ALTER TAB
LE employee ADD CONSTRAINT df_uf DEFAULT 'SP' uf FOR ALTER TABLE employee ADD CO
NSTRAINT CHECK ck_cep (zip LIKE '[0-9] [0-9] [0-9] [ 0-9] [0-9] [0-9] [0-9] [0-9
] ')
28
VIEWS (VISIONS) • • • • • • Form an alternative view of the data from one or mor
e tables of a database query permanently stored in the database as a table, but
the view does not exist physically Ideal to create specific views of certain col
umns of tables for groups of users helps to build complex queries. Views can not
be changed. It should delete and recreate it again.
CREATE VIEW AS SELECT vw_empregado d.nome nome_depto, e.nome nome_empreg, salary
FROM dept d, employee and e.cod_depto AND WHERE d.cod_depto => 18
DROP VIEW vw_empregado
29
STORED PROCEDURES Stored procedures are precompiled SQL statements that are stor
ed on the server. • The sentences are checked as the syntax and compiled the fir
st time it runs • The compiled version is stored in a cache of procedure and rec
overed from this in subsequent calls, making implementation faster and more effi
cient. • Big advantage when you have repetitive tasks to perform. Steps to creat
ing a simple procedure: 1) Write the SQL transaction 2) Test the SQL transaction
3) If the result is expected, create procedure 4) Run the procedure CREATE PROC
cont_empregados AS SELECT count (*) FROM employee EXEC cont_empregados
CURSORS
30
Sentence DEALLOCATE DECLARE OPEN FETCH CLOSE
Description Creates and sets a cursor opens a cursor declared Removes a row from
the cursor closes the cursor Removes the cursor
DECLARE CURSOR FOR SELECT cur_empregado nro_empregado, salary FROM employee nro
DECLARE @ int DECLARE @ salary numeric (10,2) OPEN cur_empregado cur_empregado F
ETCH INTO @ nro, @ salary WHILE (@ @ FETCH_STATUS = 0) BEGIN IF (@ salary> 1000)
INSERT novatab INTO VALUES (@ nro, @ salary) cur_empregado FETCH INTO @ nro, @
salary END CLOSE cur_empregado DEALLOCATE cur_empregado
31
TRIGGERS • • • Special type of stored procedure that runs when modify, include o
r exclude data from a given table is automatic Its launch Triggers can trigger c
ascading changes in related tables in the Bank.
The following example shows a trigger insert amending ytd_sales column titles in
the table every time a new row in the sales table is inserted. CREATE TRIGGER O
N intrigue sales FOR INSERT AS / * check the value of @ @ rowcount * / IF @ @ ro
wcount = 1 UPDATE SET titles ytd_sales ytd_sales + = qty FROM inserted WHERE ELS
E inserted.title_id titles.title_id = / * when rowcount is greater than 1, ** us
e the GROUP BY clause * / UPDATE SET titles ytd_sales ytd_sales + = (SELECT SUM
(qty) FROM inserted GROUP BY HAVING inserted.title_id titles.title_id = inserted
.title_id)
32
33

Das könnte Ihnen auch gefallen