Vous êtes sur la page 1sur 4

SQL: DDL y DML

Create table:
create table Alumno
(
Legajo char(7) primary key,
Nombre char(100) not null,
Apellido varchar(100) not null unique,
Telefono char(100),
IdProvincia int null references Provincia(Id)
)

Alter table:
alter table Alumno
add foreign key(IdProvincia) references Provincia(Id)
add FechaIngreso not null smalldatetime default 20120101

alter table Alumno alter column FechaIngreso not null smalldatetime default 20110101

Truncate table:
truncate table Provincia --borra todos los registros pero no la tabla

Drop table:
drop table Provincia --borra todo

Restricciones de chequeo:
alter table Alumno
add constraint restriccion1
check (Legajo between 0000000 and 9999999)

alter table Alumno drop constraint restriccion1

Vistas:
create view <nombreVista>
as
<select sin order by>

drop view <nombreVista>

Insert:
insert into Provincia(Id, Nombre) values(1, Salta)

insert into Provincia values (1, Salta) --en el orden de las columnas

insert into Provincia (Id, Nombre)
select id, nombre from OtrasProvincias where id > 200

Delete:
delete from Provincia where Id > 300

Update:
update Alumno set FechaIngreso = getdate() where Legajo = 0000001

Indices:
CREATE [UNIQUE] INDEX <nombre_indice>
ON <nombre_tabla>
(<nombre_campo> [ASC | DESC],
<nombre_campo> [ASC | DESC]
)














char(8), number, varchar(255), integer, smalldatetime, date, text, decimal(12,2)





SQL: Select

select <constantes>, <campo1, , campon>, <funciones de usuario>, <funciones de grupo>, <funciones de sistema>
from <tabla1, , tablan>, <vista1, , vistan>, <funciones de tabla1, , funciones de tablan>
where <condicion booleana>
group by <atributos>
having <condicion booleana>
order by <atributos>

select * from Cliente where Id=1 and nombre != juan
Despus de select se puede agregar DISTINCT (para que no muestre filas repetidas entre los campos que se seleccionan) y/o TOP
N (muestra mximo N registros)
Dentro de los campos que se seleccionan se puede meter otro select (subselect)

Operadores: >, <, >=, <=, !=, <>, not( ), campo between valor1 and valor2,
campo in (1, 2, 3, 4), campo in (juan, pepe gente), campo in (select ), exists(select )

Null:
campo is null
campo is not null
campo = null --da siempre falso (depende del motor)

Funcin: isnull(Nota, 0)
(si Nota es null, devuelve 0, y si no devuelve Nota)

Funciones de agregado para el group by:
count(*) --cuenta, pegundando por distinto de null
count(campo)
max(atributo)
min(atributo)
avg(atributo)
sum(atributo)

Case:
case
when cond then valor
when cond then valor
else valorPredet
end

Join:
select * from Cliente inner join Provincia on clie_idprovincia = prov_id
order by clie_idprovincia desc

Si hay clientes con clie_idprovincia en null y los queremos mostrar:
select * from Cliente left join Provincia on clie_idprovincia = prov_id

Union: Une consultas (del mismo dominio)
select from where group by having
union
select from where group by having
union
select from where group by having

order by

union omite filas repetidas idnticas: union all muestra todas

SQL: Transact SQL

declare @var int
declare @var2 char(3)

set @var1 = 1
select @var2 = jua

select @var1 = clie_idprovincia from Cliente where
--select y set hacen lo mismo, pero select deja la variable en null si la consulta tira ms de un valor o ninguno, y set lo deja como
estaba

if <condicion> <sentencia>

if <condicion> begin
<sentencias>
end

while <condicion> <sentencia>

La variable @@error si es <> de 0 indica errores

Transacciones:
begin tran

save tran

if @@error <> 0 rollback tran


commit

set transaction isolation level <nivel>

<nivel> puede ser:
read uncommited
read commited
repeatable read
serializable

La variable @@trancount tiene el nivel de transaccin anidada en el que estamos

Cursores:
declare nombre_cursor cursor [scroll/insensitive]
for <select statement>
[for update c1, , cn]

open nombre_cursor
fetch next from nombre_cursor into @var1, @var2
while @@fetch_status = 0 begin


fetch next from nombre_cursor into @var1, @var2
end

close nombre_cursor
deallocate nombre_cursor

Funciones:
create function nombre_funcion(@param1 as tipo)
returns tipo
as begin

end

Stored procedures:
create procedure nombre_procedure(@param1 as tipo, @param2 as tipo2)
as begin

end

Para ejecutarlos:
exec nombre_procedure parametro, 4

Triggers:
create trigger elTrigger on tabla
<after/instead of> <insert/update/delete>
as begin

--tablas inserted y deleted
end

drop function dbo.nombreFuncion
drop procedure dbo.nombreProcedure
drop trigger dbo.nombreTrigger

Vous aimerez peut-être aussi