Professional Documents
Culture Documents
Datos Relacionales
Parte 3
Ambiente de ejecucin
El cdigo se puede ejecutar en:
Cliente
Servidor
Batch
Una o ms sentencias enviadas y ejecutadas como
una sola
Ejemplo:
delete sales
where stor_id = "5023"
and ord_num = "AB-123-DEF-425-1Z3"
delete salesdetail
where stor_id = "5023"
and ord_num = "AB-123-DEF-425-1Z3"
select * from sales
where stor_id = "5023"
select * from salesdetail
where stor_id = "5023"
go
create default
create rule
create procedure
create trigger
declare cursor
Comentarios
Porcin de cdigo ignorado por el servidor
Usados para documentar
Dos formas:
Variables locales
Ejemplos:
declare
@number int,
@copy int,
@sum int
select
@number = 10
select
@copy = @number,
@sum = @number + 100
Ejemplos:
declare @AD_id char(11)
select @AD_id = au_id
from authors
where au_fname = "Ann" and au_lname = "Dull"
update table_name
set {column_name | variable_name } = expression
[, {column_name | variable_name } = expression ... ]
[where condition]
Ejemplos:
declare @pub_name varchar(40)
update publishers
set
city = "Escanaba",
state = "MI",
@pub_name = pub_name
where pub_id = "0736"
Ejemplo
Las variables se deben declarar antes de usarlas
Ejemplo:
select pub_id
from publishers
select @myvar = total_sales
from titles
where title_id = "BU2075"
select @myvar
Server Message:
Line 3:
Number
137, Severity
15
Ejemplo
Los valores de las variables deben de concordar con
el tipo de dato de la variable
Ejemplo:
declare @myvariable int
select @myvariable = title
from titles
where title_id = "BU2075"
select @myvariable
Server Message: Number 257, Severity 16
Line 2:
Implicit conversion from datatype 'VARCHAR' to
'INT' is not allowed. Use the CONVERT function to
run this query.
Ejemplo
Si el select no retorna valores, la variable no cambia
Ejemplo:
declare @value int
select @value = total_sales from titles
where title_id = "BU2075"
select @value as "BU2075 sales"
select @value = total_sales from titles
where title_id = "BU11" -- should be "BU1111"
select @value as "BU1111 sales"
Primer query:
BU2075 sales
-----------18722
Segundo query:
BU1111 sales
-----------18722
Ejemplo
Las variables locales se borran al terminar el batch que las
crea
-- Declare a local variable:
declare @pub_var char(4)
-- Assign the variable a value from a table:
select @pub_var = pub_id
from pubs2..publishers
where pub_name = "New Age Books"
-- View the variables value:
select @pub_var
Variables globales
Ejemplo
Ejemplo:
delete from titles
where type = "popular_comp"
select @@rowcount
-----3
Ejemplo
Ejemplo:
delete from titles
where type = "popular_comp"
select @@error
-----0
Ejemplo
Ejemplo:
-- The word "from" is misplaced
delete titles from
where type = "psychology"
Server Message: Number 156, Severity 15
Line 4:
Incorrect syntax near the keyword 'where'.
select @@error
-----156
Ejemplo
Crear una tabla:
select * into mytitles
from pubs2..titles
if...else
begin...end
if exists
while
break
continue
return
if...else
Sintaxis simplificada:
if condition
block_to_execute_when_condition_is_true
[ else
block_to_execute_when_condition_is_false ]
Ejemplo:
delete from titles
where type = "mod_cook"
if @@error <> 0
select "An error has occurred!"
else
select "The delete was successful."
Condiciones anidadas
Ejemplo:
delete from titles
where type = "mod_cook"
if @@rowcount = 0
select "No rows were deleted."
else
if @@rowcount = 1
select "One row was deleted."
else
select "Multiple rows were
deleted."
begin...end
Sintaxis:
begin
statement
statement
...
end
Ejemplo:
...
if @temp_id = "TC4203"
begin
select @temp_type = "trad_cook"
delete titles where type = "trad_cook"
end
else
begin
select "Title has already been deleted"
end
if exists
Sintaxis simplificada:
if [ not ] exists ( select_statement )
code_to_execute_when_condition_is_true
[ else
code_to_execute_when_condition_is_false ]
Ejemplo:
if exists (select * from titles
where price > $50.00)
update titles set price = price * $0.90
else
select "All titles priced under $50.00"
Ejemplo
Ejemplo:
if exists (select * from sysobjects
where name = "vw_utah_authors"
and type = "V")
drop view vw_utah_authors
go
create view vw_utah_authors
as
select * from authors
where state = "UT"
with check option
Sentencias if
Ejemplo:
if (select avg(price) from pubs2..titles) >
$25
select "These books are expensive."
else
select "These books are a bargain."
Ejemplo :
drop table mysales
Ejemplo :
if exists (select * from sysobjects
where name = "mysales"
and type = "U")
drop table mysales
while
Sintaxis:
while condition
block_to_execute
Ejemplo:
while (select avg(price) from titles) < $40
begin
update titles
set price = price + $2
end
Ejemplo
Ejemplo:
declare @price money
select @price = price
from titles
where title_id = "PS1372"
while @price < $30
begin
update titles
set price = price * $1.10
where title_id = "PS1372"
end
-----
break
Ejemplo:
-----
continue
Ejemplo:
-- While @price is less than $20, this loop adds
-- $1 to @price. If there are 5 or more titles
-- at @price, it restarts the loop. Otherwise,
-- it increases all books priced at @price by 10%.
...
while @price < $20.00
begin
select @price = @price + $1.00
if (select count(price) from titles
where price = @price) >= 5
continue
else
update titles
set price = price * $1.10
where price = @price
end
return
Ejemplo:
-----
Ciclos while
Ejemplo:
declare @x money
select @x = $0
while @x < (select max(price) from
pubs2..titles)
begin
select @x = @x + $1
select "Titles less than $", @x
select price, title
from pubs2..titles
where price < @x
end
select
Sintaxis simplificada:
select { "user_message" | variable_name | column_list }
Ejemplo:
select "The average price is too low."
select "The average price is ", @avg_price
select "The average price is ", avg(price)
from titles
Procedimientos almacenados
Un procedimiento almacenado es un conjunto de sentencias
SQL y de control de flujo
Beneficios de los procedimientos almacenados:
Triggers
Procedimientos extendidos
Interactive Execution
Ventajas en el rendimiento
Un procedimiento almacenado se ejecuta ms rpido que un
batch porque:
El procedimiento almacenado ya ha sido analizado
Ya se han resuelto las referencias a los objetos
referenciados en el procedimiento almacenado
No se necesita construir el rbol de bsqueda, l usa el que
se hace en el momento de compilarlo
No se necesita crear un plan de bsqueda, porque ya el
procedimiento tiene uno
Ejemplo:
create proc proc_update_titles
as
update titles
set price = price * $0.95
where total_sales < 3000
return
Ejemplo:
drop proc proc_update_titles
Ejemplo:
execute proc_update_titles
Variables
Los procedimientos almacenados pueden crear y usar
variables locales
Las variables slo existen mientras exista el procedimiento
Las variables no las puede usar otro proceso
Ejemplo:
create proc proc_update_under_half_titles
as
declare @max_sales int, @half_max real
select @max_sales = max(total_sales)
from titles
select @half_max = @max_sales / 2
select title, total_sales from titles
where total_sales < @half_max
update titles
set price = price * $0.95
where total_sales < @half_max
return
use database
create view
create default
create rule
create procedure
create trigger
Ejemplo:
grant execute
on proc_update_titles
to tjovanka, vturlough, pbrown
Ejecutar el procedimiento:
exec proc_hello
Parmetros de entrada
An input Parmetro is a variable local to a
procedimiento almacenado that can receive
a value from the exec procedure Sentencia
Ejemplo:
create proc proc_author_info
(@lname varchar(40), @fname varchar(20))
as
-- lists the author and his or her books
select au_lname, au_fname, title
from authors, titles, titleauthor
where au_fname = @fname
and au_lname = @lname
and authors.au_id = titleauthor.au_id
and titles.title_id = titleauthor.title_id
return
Pasar parmetros
Dos mtodos para pasar valores a parmetros:
Paso de parmetros por posicin
Paso de parmetros por nombre
Ejemplo:
exec proc_author_info "Ringer", "Albert"
au_lname
-------Ringer
Ringer
au_fname
-------Albert
Albert
title
-----
Ejemplo:
exec proc_author_info
@lname = "Ringer", @fname = "Albert"
au_lname
-------Ringer
Ringer
au_fname
-------Albert
Albert
title
----Is Anger the Enemy?
Life Without Fear
au_lname
-------White
Green
...
state
----CA
CA
au_fname
-------Johnson
Marjorie
Parmetros de entrada
Crear un procedimiento almacenado que tenga un parmetro de
entrada:
create proc proc_hello_param (@name varchar(30))
as
print "Hello %1!", @name
return
Parmetros de entrada
Ejecutar el procedimiento con y sin un valor para el
parmetro de entrada:
exec proc_hello_def
exec proc_hello_def "<yourname>"
Retorno de valores
A return Parmetro is a variable local to a
procedimiento almacenado that can send a
value to the exec procedure Sentencia
Ejemplo:
create proc proc_new_price
(@title_id char(6),
@new_price money output)
as
select @new_price = price
from titles
where title_id = @title_id
select @new_price = @new_price * $1.15
return
Ejemplo:
declare @my_title char(6), @my_price money
select @my_title = "PC8888"
exec proc_new_price
@my_title, @my_price output
---------23.00
@qty_ordered
int,
@actual_qty
int,
@item_ordered
char(10)
select @qty_ordered = 50
select @actual_qty
= @qty_ordered
select @item_ordered = "1095-87654"
exec proc_dec_inventory @item_ordered, @actual_qty output
-- additional processing here.
-- Includes error handling, etc.
select "Quantity shipped is " +
convert(char(10),@actual_qty) + " out of " +
convert (char(10), @qty_ordered)
Legibilidad
Para hacer un cdigo ms legible:
Utilizar comentarios
Utilizar indentacin
Usar espacios en blanco y dejar el cdigo
organizado en columnas
Declarar e iniciar las variables en un bloque
Legibilidad - ejemplo
create proc proc_insert_titleauthor
(@tid
char(6)
= NULL,
@aid
char(11)
= NULL,
@au_ord tinyint
= NULL,
@royal
int
= NULL)
as
/***************************************************
****************************************************
** Stored Procedure:proc_insert_titleauthor
** Creation Date: 4/1/95
** Author: D. Normalize
Legibilidad - ejemplo
**
**
**
**
**
**
**
**
**
**
**
**
**
**
**
**
**
**
**
Purpose:
Receives four parameters containing values that are
inserted into the titleauthor table of the pubs2 database. Sets default parameter values as required for
error checking and usage confirmation. Verifies referential integrity in the titles and authors tables.
Inserts these parameter values into the table. Rolls
back the transaction and returns a custom error
message and return status if the insertion fails.
Input Parameters:
@tid
the title id of the book, default is NULL
@aid
the author id of the author of the book,
default is NULL
@au_ord the author number (1-n) for counting the
number of authors for the book, default is
NULL
@royal percentage of the royalty received by the
author (0 to 100), default is NULL
Legibilidad - ejemplo
** Return Parameters: <none>
**
** Return Status:
**
-500
Incorrect usage
**
-200
Insertion failed
**
-405
Referential integrity check failed
**
** Usage:
**
declare @retstatus int
**
exec @retstatus=proc_insert_titleauthor @tid,
**
@aid,
**
@au_ord,
**
@royal
** Local Variables
**
@err
stores the error number resulting from command
** execution
Legibilidad - ejemplo
**
Called by:
**
any calling program run by a user with execute
**
permission on this stored procedure
**
** Calls:<none>
**
** Data Modifications:
**
inserts new data into the titleauthor table
**
** Updates:
**
Date
Author
Changes
**
5/1/95
A. Bug
specified default values
*********************************************************/
Legibilidad - ejemplo
declare @err int
/* Check for required parameters. */
if (@tid is NULL or @aid is NULL)
begin
raiserror 30010 "Usage:proc_insert_titleauthor title_id,
au_id"
return -500
end
begin transaction
/* Check that the title_id and au_id passed to this
** procedure are valid values in the titles and author
** tables respectively. If not, return an error message. */
Legibilidad - ejemplo
if exists (select * from titles where title_id=@tid)
and exists (select 1 from authors where au_id =@aid)
begin
insert titleauthor values(@aid,@tid,@au_ord,@royal)
if @@error <> 0
begin
rollback transaction
raiserror 21005 "Insertion into titleauthor
failed.
Transaction failed."
return -200
end
end
else /* Referential Integrity check failed. */
begin
rollback transaction
raiserror 30020 "title_id or au_id not valid"
return -405
end
commit transaction
return
go
sp_procxmode
sp_procxmode permite ver y cambiar el modo de transaccin de un
procedimiento
Sintaxis:
Ejemplo:
sp_procxmode proc_update_titles, unchained
Ejecutar el procedimiento:
exec tagtest
Ejecutar el procedimiento:
exec tagtest
Meaning
Greater than 0
Successful completetion
-1 through 99
System-detected error
Less than 99
Ejemplo:
create proc proc_datacheck
as
if (select max(total_sales) from titles) < 3000
begin
print "All the books have sold
less than 3000."
return 100
end
else
...
return 0
Ejemplo:
declare @status int
exec @status = proc_datacheck
if @status = 100
exec proc_max_under_3000
else
print "proc_datacheck was successful"
Rollbacks no intencionales
Un rollback no intencional es un rollback anidado que sin intencin
deshace el trabajo en transacciones externas
Proc1(Transaccin ms externa)
begin tran
<statements...>
if <error>
begin
rollback tran
return
end
exec proc2
if <error>
begin
rollback tran
return
end
<statements...>
commit tran
return
Proc2(Procedimiento aniddo)
begin tran
<statements...>
if <error>
begin
rollback tran
return
end
<statements...>
commit tran
return
proc 1
proc 2
if <error>
rollback tran xyz(4)
else ...
if @ret_status = -999
-- Did called proc fail?
begin
-- to rollback or continue.
rollback tran proc1_tran
return -999
end
if @tran_flag = 0
-- this proc executed begin tran
commit tran proc1_tran
-- no need to commit with save tran
return
Planes de bsqueda
Un plan de bsqueda es un conjunto ordenado de etapas que se
requieren para acceder los datos, incluyendo informacin sobre:
Si usar o no un ndice
El ndice a usar
El orden en el cual las tablas se deben encadenar
sp_recompile
sp_recompile hace que cada procedimiento
almacenado (y trigger) que utilice la tabla indicada
se recompile la siguiente vez que l se ejecute
Sintaxis:
sp_recompile table_name
Ejemplo:
sp_recompile authors
Trigger
Un trigger es un procedimiento almacenado asociado
con una tabla, el cual se ejecuta automticamente
cuando se modifica un dato de esa tabla
User-Defined
Can It Be
Can It Be
Can It Use
Explicitly
Executed
Parameters?
Called?
Automatically?
Yes
No
Yes
No
Yes
No
Stored
Procedure
Trigger
Definicin de un trigger
Un trigger se define asociado con una tabla para una o
ms sentencias de manipulacin de datos
Un trigger se puede definir para insert, update, o delete o
cualquier combinacin de ellos
Activacin de un trigger
Cuando se modifica un dato en una tabla que tiene declarado
un trigger para esa sentencia, el trigger se dispara
El trigger se dispara una vez, independientemente del nmero de filas
afectadas
El trigger se dispara aunque no hayan filas afectadas
Llamarse directamente
Usar parmetros
Definirse sobre tablas temporales o vistas
Crear objetos permanentes de base de datos
Crear triggers
Sintaxis simplificada:
Ejemplo:
create trigger trg_i_sales
on sales
for insert
as
if datename (dd,getdate()) = "Sun"
begin
raiserror 40070, "Sales cannot be
processed on Sunday."
rollback trigger
end
Borrar Triggers
Sintaxis simplificada:
drop trigger trigger_name
Ejemplo:
drop trigger trg_i_sales
sp_help trigger_name
sp_helptext trigger_name
Triggers - ejemplo
Crear dos tablas:
select * into myauthors
from pubs2..authors
create table myrecord (
mytime
myrows
)
datetime,
int
Triggers - ejemplo
Ejecutar un delete y ver la tabla myrecords:
delete from myauthors
where state = "CA"
select * from myrecord
Borrados
A delete adds rows to the deleted table
Inserciones
An insert adds rows to the inserted table
Actualizaciones
An update adds rows to both tables
update titles
set total_sales = isnull(total_sales, 0) +
(select sum(qty)
from inserted
where titles.title_id = inserted.title_id)
where title_id in (select title_id from inserted)
update titles
set total_sales = isnull(total_sales, 0) (select sum(qty)
from deleted
where titles.title_id = deleted.title_id)
where title_id in (select title_id from deleted)
return
Triggers y rollbacks
Tres tipos de rollbacks:
Deshacer el trigger
Deshacer el trigger y la sentencia que lo dispar
Deshacer toda la transaccin
Deshacer un trigger
Para deshacer un trigger, declarar un punto de grabacin y luego hacer el rollback
Un rollback sin punto de grabacin deshace toda la transaccin
Procedimiento almacenado
Caso A
begin tran
...
insert ...
print "in sp"
...
commit tran
print "sp done"
Trigger
save tran s1
....
rollback tran s1
print tr done
return
Procedimiento almacenado
Caso B
(este caso
ocaciona un
error)
begin tran
...
insert ...
print "in sp"
...
commit tran
print "sp done"
Trigger
begin tran s2
....
rollback tran s2
print tr done
return
Deshacer un trigger
rollback trigger deshace el trigger y la sentencia que lo
dispar
Sintaxis:
Ejemplo:
create trigger trg_i_publishers
on publishers
for insert
as
if @@rowcount > 1
begin
rollback trigger with raiserror 40031
"You cannot insert more than one
publisher at a time."
return
end
Deshacer un trigger
Procedimiento almacenado
Case C
begin tran
...
insert ...
print "in sp"
...
commit tran
print "sp done"
Trigger
....
....
rollback trigger
print tr done
return
Procedimiento almacenado
Case E
begin tran
...
insert ...
print "in sp"
...
commit tran
print "sp done"
begin tran
...
rollback tran
print "tr done
return
Trigger
....
....
Rollback tran
print tr done
return
Triggers y rollbacks
------
Triggers y rollbacks
-- 1) only one title at a time
if @num_rows > 1
begin
rollback trigger with raiserror 20011
"Can only update or add one title at a time."
return
end
-- 2) occurs during the work week
if (select datepart(dw, getdate())) in (1, 7)
begin
rollback trigger with raiserror 20012
"Can only update price during work day."
return
end
Triggers y rollbacks
-- 3) the price changes by 10% or less
if (select new.price/old.price
from inserted new, deleted old)
not between 1.10 and 0.90
begin
rollback trigger with raiserror 20013
"Can only change price by 10 percent."
return
end
-- 4) only books with sales > 0
if (select isnull(total_sales, 0) from inserted) <= 0
begin
rollback trigger with raiserror 20014
"Can only change price of book with sales."
return
end
return
go
@@rowcount
if update
triggers anidados
triggers recursivos
if update
if update es una condicin que le permite a un trigger
chequear si ha habido un cambio en una determinada
columna
Slo se puede usar en triggers
Usualmente se usa para chequear si el valor de una
llave primaria ha cambiado
Sintaxis simplificada:
if update
-- Update trigger on publishers table
create trigger trg_u_publishers
on publishers
for update
as
-- Find out how many rows were modified
declare @num_rows int
select @num_rows=@@rowcount
if @num_rows=0
return
if update
if update ( pub_id ) -- Was primary key updated?
begin
-- Multiple updated rows not allowed
if @num_rows > 1
begin
raiserror 31113 "Updates to primary
keys of multiple rows is not permitted."
rollback transaction
return
end
-- Cascade update to titles table
update titles
set t.pub_id = new.pub_id
from titles t, inserted new, deleted old
where t.pub_id = old.pub_id
end
return
Triggers anidados
Un trigger anidado es un trigger que se dispara en respuesta
a una modificacin hecha en un trigger
Triggers recursivos
Un trigger recursivo es aquel que se dispara cuando
modifica su propia tabla
Entity Integrity
Referential
Integrity
Constraints
Check
constraints
Primary key
constraints,
unique
constraints
References
constraints
Database
Objects
Rules
Indexes
Triggers
Restricciones
Triggers
Permitido
Permitido
Permitido
Permitido
No permitido*
Permitido
Permitido
Permitido
No permitido*
Permitido
Permitido
Permitido
Ejemplo
Ejemplo para mantener la integridad referencial de la llave fornea cuando se
inserta o actualiza la tabla salesdetail:
create trigger trg_iu_sales
on salesdetail
for insert, update as
declare @num_rows int
select @num_rows = @@rowcount
if @num_rows = 0
return
if (select count (*)
from titles t, inserted i
where t.title_id = i.title_id)
<> @num_rows
rollback transaction
if (select count (*) from
sales s, inserted i
where s.stor_id = i.stor_id
and s.ord_num = i.ord_num)
<> @num_rows
rollback transaction
return
Ejemplo
Ejemplo para mantener la integridad referencial de la llave fornea cuando se
inserta o actualiza la tabla salesdetail:
create trigger trg_du_titles
on titles
for delete, update as
-- prevent delete or update of
-- title_id if there are foreign key
-- values that reference them
..
return
create trigger trg_du_sales
on sales
for delete, update as
-- prevent delete or update of
-- stor_id/ord_num if there are
-- foreign key values that
-- reference them
...
return
Restricciones vs triggers
Ventajas de las restricciones:
Las restricciones (y reglas) son ms rpidas que los triggers
Las restricciones no requieren codificacin adicional
Es mejor para chequear datos antes de ingresarlos a la base
de datos
$SYBASE/install/errorlog
Sybase
1
$SYBASE/install/
RUN_SYBASE
$SYBASE/charsets (dir)
$SYBASE/locales (dir)
4
10
5
$SYBASE/sybase.cfg
userdb
13
/devices/datadev.dat
$SYBASE/master.dat
sybsystemprocs
12
$SYBASE/sysprocs.dat
SYBASE
Memory
Network
Backup/Recovery
Operating
Operating System
System
I/O
Locking
master
sysobjects
sysindexes
sysdatabases sysusages
...
...
syscolumns
copies model
sysobjects
user database
sysindexes
...
syscolumns
Inserta
informacin
de las bases
de datos en
tablas del
sistema
9 AM
10 AM
Dump
Database
Dump
Tran 1
Dump
Tran 2
10:30 AM
Create/Load
Database
Load
Tran 1
Load
Tran 2
pubs2.dbo.publishers
pub_id
city
pub_id pub_name
pub_name
city
0736
Boston
0736 New
NewAge
Age
Boston
0877
Washington
0877 Binnet
Binnet
Washington
1389
Berkeley
1389 Algodata
Algodata
Berkeley
U1
U1
U2
U2
L5
L5
U3
U3
L6
L6
L7
L7
L8
L8
L9
L9
U4
U4
Logins
alias
alias dbo
db
db
t1
t1
Permisios
L3
L3
L4
L4
PILOS
PILOS
GUEST
GUEST
LOCHOS
LOCHOS
L1
L1
L2
L2
A nivel de objetos/comandos
PUBLIC
view
view
t2
t2
sp 11
sp
t3
t3
sp 22
sp
sp 33
sp
sp 44
sp
t4
t4
Vistas y
Tablas
procedimientos
almacenados
Logins
Usuario
Servidor - Login
Todos los clientes deben dar un nombre de cuenta (login) y
palabra clave (password) vlidos antes de ingresar al servidor
o a las bases de datos
Nombre de la cuenta (login)
Nombre asignado por el administrador del sistema al cual se le asocia
un mtodo para validacin (por ejemplo el password)
Debe corresponder a una sola persona
Se maneja a nivel del servidor
Roles
Tres tipos de roles en ASE:
SSO (System Security officer)
OPER (Operator)
SA (System Administrator)
Usuarios y grupos
Usuario
Mediante un login puede acceder a una base de datos; all
debe estar definido como un usuario de esa base de datos
Un usuario puede tener mltiples logins
Grupo
Nombre asignado a un conjunto de usuarios de una base de
datos
Mecanismo que busca simplificar la administracin
Usuarios en grupos
Todos los usuarios son miembros del grupo public
Un usuario puede pertenecer slo a otro grupo
Rol DBO
El DBO (database owner) es un usuario especial de la base
de datos
Tpicamente, tiene un login asociado
El dbo puede:
Rol guest
Cada vez que se crea una nueva base de datos, la estructura
inicial se copia de la base de datos model
Por default, la base de datos model no tiene el usuario guest
Si se crea el usuario guest en la base de datos model, todas las
nuevas bases de datos creadas tambin lo tendrn
Todos los logins se tratan como un usuario guest en una base de
datos si:
Existe el usuario guest en esa base de datos
Los logins no estn explcitamente asociados con un usuario de esa base
de datos
Los logins que se tratan como usuario guest, toman los permisos
que tenga definido el usuario guest
El group public
Todas las bases de datos tienen un grupo llamado
public, el cual no se puede borrar
Todos los usuarios siempre estn asociados con el
grupo public, aun si explcitamente estn definidos en
otro grupo
Un usuario puede asociarse a un grupo, adems del
grupo public
La precedencia del conjunto de permisos est determinado
de forma cronolgica
Jerarqua de permisos
Administradores
Administradores del
del Sistema
Sistema
Database
Database Owners
Owners
Propietarios
Propietarios de
de Database
Database Objects
Objects
Otros
Otros Usuarios
Usuarios
Objeto
Objeto
Tabla,
Tabla,vista,
vista,columnas
columnas
Tabla,
Tabla,vista
vista
Tabla
Tabla
Procedimiento
Procedimientoalmacenado
almacenado
create database
create default
create table
create view
Defaults To
Statement
System
Database Object
Operator
Admin
Owner Owner
Public
Yes
No
alter table
create database
create default
create index
create rule
N/A
Defaults To
Statement
System
Database Object
Operator
Admin
Owner Owner
create table
create trigger
create view
delete
disk init
drop (any object)
Public
(1)
Yes
No
(1)
(2)
N/A
Defaults To
Statement
System
Database Object
Operator
Admin
Owner Owner
dump database
dump transaction
execute (3)
grant on object
grant command
insert
Public
Yes
No
(2)
No means use of the command is never
restricted
N/A means use of the command is always
restricted
N/A
Defaults To
Statement
System
Database Object
Operator
Admin
Owner Owner
load transaction
print
revoke on object
revoke command
select
set
update
(1) public can create temporary tables, no permission required
(2) If a view, permission defaults to view owner
(3) Defaults to store procedure owner
Public
Yes
No
(2)
(3)
No means use of the command is never
restricted
N/A means use of the command is always
restricted
N/A
Auditoria
La auditoria permite registrar las actividades del sistema con el fin
de detectar el accesos no autorizados o el mal uso de los recursos
del sistema
Esas actividades se pueden grabar en una base de datos