Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
1.
2.
3.
USANDO TRANSACT-SQL
USANDO TRANSACT-SQL
10/03/2010
USANDO TRANSACT-SQL
DDL
CREATE
ALTER
DROP
DCL
GRANT
DENY
REVOKE
USANDO TRANSACT-SQL
DML
SELECT
INSERT
UPDATE
DELETE
10/03/2010
Comando
Crear registros
Actualizar registros
UPDATE Production.UnitMeasure
SET Name = N'Pie Cuadrado'
WHERE UnitMeasureCode= 'F2'
Borrar Registros
U
D
USANDO TRANSACT-SQL
USANDO TRANSACT-SQL
10/03/2010
USANDO TRANSACT-SQL
USANDO TRANSACT-SQL
10/03/2010
2.
3.
4.
USANDO TRANSACT-SQL
USANDO TRANSACT-SQL
10
10/03/2010
USANDO TRANSACT-SQL
11
USANDO TRANSACT-SQL
12
10/03/2010
Convencin de Nombres
Usar una convencin de nombre consistente
Por ejemplo poner los nombres de las tablas en plural y los nombres de los
campos en singular.
No usar caracteres especiales.
Incluso no utilizar espacios para evitar usar [].
Si dos campos de diferentes tablas contienen los mismos datos,
entonces nmbrelos iguales.
No utilizar nombre vagos como Id
Utilizar nombres que tengan significado.
Por ejemplo utilice StudentPreferredCourses en lugar de StudPrfCrs
SQL Server - Programacin
USANDO TRANSACT-SQL
13
Delimitando Objetos
Se debe evitar utilizar palabras reservadas en nombres de
tablas o campos.
Si no es posible evitarlo entonces puede utilizar
delimitadores.
USANDO TRANSACT-SQL
14
10/03/2010
Comentarios
Comentarios de bloques comienzan
con /* y terminan con */
/************************************************
* spInsProduct - Inserts product records
*
* Accepts ProductName, StandardPrice, QtyInStock, CategoryID
* Returns new ProductID, Int
*
* Created: 6-12-08 (Paul Turley)
*
* Revisions:
* 7-10-08 - (Dan Wood) Added MarkupPercent parameter
* 7-12-08 - (Paul Turley) Changed MarkupPercent parameter data type from
* int to decimal(10,2)
************************************************/
USANDO TRANSACT-SQL
15
ALTER
DROP
USANDO TRANSACT-SQL
16
10/03/2010
PRCTICA 2-03
USANDO TRANSACT-SQL
17
PRCTICA 2-04
USANDO TRANSACT-SQL
18
10/03/2010
PRCTICA 2-05
/******************************************************
* Checks for existing Product record
* If exists, updates the record. If not,
* inserts new record
******************************************************/
CREATE PROCEDURE uspInsertOrUpdateProduct
-- Input parameters -@ProductName nvarchar(50)
,@ProductNumber nvarchar(25)
,@StdCost money
AS
IF EXISTS(SELECT * FROM Production.Product
WHERE ProductNumber = @ProductNumber)
UPDATE Production.Product
SET Name = @ProductName, StandardCost = @StdCost
WHERE ProductNumber = @ProductNumber
ELSE
INSERT INTO Production.Product
(
Name , ProductNumber , StandardCost
,MakeFlag ,FinishedGoodsFlag ,SafetyStockLevel
,ReorderPoint ,ListPrice ,DaysToManufacture
,ProductLine ,SellStartDate ,ModifiedDate
)
SELECT
@ProductName,@ProductNumber,@StdCost
,0,0,1
,1,0,0
,'S',SYSDATETIME(),SYSDATETIME()
USANDO TRANSACT-SQL
19
PRCTICA 2-06:
1. Ejecutar las instrucciones a la
izquierda en el editor de consultas
para crear la funcin
2. Buscar la funcin en el explorador de
objetos:
[AdventureWorks] [Programmability] [Functions]
[Scalar-valued Functions] [dbo_fn_LastOfMonth]
3. Comprobar el funcionamiento de la
funcin ejecutando la siguiente
instruccin
SELECT dbo.fn_LastOfMonth('2010-03-03')
USANDO TRANSACT-SQL
20
10
10/03/2010
Ao (yy, yyyy),
trimestre (qq, q),
mes (mm, m),
da del ao (dy, y),
da (dd, d),
semana (wk, ww),
hora (hh),
minuto (mi, n),
segungo (ss, s),
milisegundo (ms),
microsegundo (mcs),
nanosegundo (ns)
USANDO TRANSACT-SQL
21
PRCTICA 2-07:
1. Crear el disparador
2. Comprobar el funcionamiento del
disparador intentando actualizando el
registro que se creo en la prctica anterior
con el siguiente comando
UPDATE Production.Product
SET Name='UNI'
WHERE ProductID=1005
USANDO TRANSACT-SQL
22
11
10/03/2010
USANDO TRANSACT-SQL
23
Modificando Vista
PRCTICA 2-09
Instrucciones
USE [AdventureWorks]
GO
USANDO TRANSACT-SQL
24
12
10/03/2010
DROP
DROP
DROP
DROP
DROP
TABLE Appointment
VIEW vwProductByCategory
PROCEDURE uspInsertOrUpdateProduct
TRIGGER Production.tr_UpdProduct
FUNCTION dbo.fn_LastOfMonth
USANDO TRANSACT-SQL
25
Ejemplo de Comandos
GRANT SELECT ON Production.Product TO Paul
GRANT EXECUTE ON spAddProduct TO db_datawriter
DENY EXECUTE ON spAddProduct TO Martha
GRANT SELECT, INSERT, UPDATE ON Production.Product TO Paul
GRANT UPDATE ON dbo.PublishedBooks TO Authors
DENY SELECT ON dbo.PublishedBooks TO Paul
SQL Server - Programacin
USANDO TRANSACT-SQL
26
13
10/03/2010
Ejercicio 1
1. Abrir el SSMS
2. Seleccionar la base de datos AdventureWorks
por defecto
3. Ejecutar las siguientes instrucciones
SELECT * FROM Production.Product
USANDO TRANSACT-SQL
27
Ejercicio 2
Insertar un registro utilizando un script SQL generado
1. Usando el SSMS posicinese sobre la tabla
[Production.ProductCategory].
2. Presione Botn derecho y seleccionar [Script Table as]
[INSERT To] [New Query Editor Window]
3. Actualice los parmetros de la consulta seleccionando en
el men [Query] [Specify Values for Template
Parameters+. Se abre la pantalla *Specify Values for
Template Parameter]
4. En la pantalla con la lista de parmetros escriba 'Widgets'
con comilla simple para [Name] y DEFAULT para los otros
dos campos.
5. Verificar que el registro fue aadido por medio de una
consulta SELECT a la tabla.
SQL Server - Programacin
USANDO TRANSACT-SQL
28
14