14
 10/03/2010 1 Prof. Marlon S. Ramírez M. Curso de Microsoft SQL Server Programación Unidad 2 - Usando T ransact-SQL (12hrs) 1. Ca teg oría de Consulta s ( DDL, DCL y DML) 2. Rec up eración de los da to s 3. Funciones y Agregación Prof. Marlon S. Ramírez M. USANDO TRANSACT-SQL 1. Cate goa de Consul tas ( DDL, DCL y DML ) 2. Recuperación de los da to s 3. Funcione s y Agr egación SQL Server - Programación USANDO TRANSACT-SQL 2

Curso SQL Server Prog U2-02

Embed Size (px)

DESCRIPTION

Curso SQL Server Prog U2-02

Citation preview

  • 10/03/2010

    1

    Prof. Marlon S. Ramrez M.

    Curso de Microsoft SQL Server Programacin

    Unidad 2 - Usando Transact-SQL (12hrs) 1. Categora de Consultas (DDL, DCL y DML)2. Recuperacin de los datos3. Funciones y Agregacin

    Prof. Marlon S. Ramrez M.

    USANDO TRANSACT-SQL

    1. Categora de Consultas (DDL, DCL y DML)

    2. Recuperacin de los datos

    3. Funciones y Agregacin

    SQL Server - Programacin USANDO TRANSACT-SQL 2

  • 10/03/2010

    2

    Prof. Marlon S. Ramrez M.

    Tres diferentes Categoras de Consulta

    Lenguaje de definicin de datos (DDL - Data Definition Language). Las instrucciones DDL son usadas para crear y manejar los objetos en

    la base de datos. Estas pueden ser usadas para crear (CREATE), modificar (ALTER) y borrar (DROP) base de datos BD, tablas, ndices, vistas, procedimiento almacenado y otros objetos.

    Lenguaje de control de datos (DCL Data Control Language) Las instrucciones DCL controlan los permisos de seguridad para

    usuarios y objetos de la BD. Se puede otorgar (GRANT) o negar (DENY) estos permisos para un usuario especfico o usuarios que pertenecen a un rol en la BD o grupo de usuario Windows.

    Lenguaje de manipulacin de datos (DML Data ManipulationLanguage) Las instrucciones DML son usadas para trabajar con los datos. Estas

    incluyen instrucciones para obtener informacin (SELECT), insertar filas en una tabla (INSERT), modificar valores (UPDATE) y borrar filas (DELETE)

    SQL Server - Programacin USANDO TRANSACT-SQL 3

    Prof. Marlon S. Ramrez M.

    Resumen de Comandos segn tipo de Consulta

    SQL Server - Programacin USANDO TRANSACT-SQL 4

    DDL

    CREATE ALTER DROP

    DCL

    GRANT DENY REVOKE

    DML

    SELECT INSERT UPDATE DELETE

  • 10/03/2010

    3

    Prof. Marlon S. Ramrez M.

    Las instrucciones bsicas de DML

    Letra Operacin Comando

    CCrear registros INSERT INTO Production.UnitMeasure

    VALUES (N'F2', N'Square Feet', GETDATE())

    R

    Leer Registros (READ) SELECT Name, ProductNumber, ListPrice AS Price FROM Production.ProductWHERE ProductLine = 'R' AND DaysToManufacture < 4 ORDER BY Name ASC

    UActualizar registros UPDATE Production.UnitMeasure

    SET Name = N'Pie Cuadrado'WHERE UnitMeasureCode= 'F2'

    DBorrar Registros DELETE FROM Production.ProductCostHistory

    WHERE StandardCost > 1000.00

    SQL Server - Programacin USANDO TRANSACT-SQL 5

    Prof. Marlon S. Ramrez M.

    PRCTICA 2-01a: SELECT

    Mostrar el nombre, nmero de producto y precio de todos los productos de la lnea R con menos de cuatro das de haberse fabricado.1. En nueva pantalla de editor de consultas, ejecutar

    SELECT Name, ProductNumber, ListPrice AS Price

    FROM Production.ProductWHERE ProductLine = 'R' AND DaysToManufacture < 4 ORDER BY Name ASC

    2. Verificar que los productos cumplan con las condiciones mencionadas.

    SQL Server - Programacin USANDO TRANSACT-SQL 6

  • 10/03/2010

    4

    Prof. Marlon S. Ramrez M.

    PRCTICA 2-01b: INSERTAgregar una nueva unidad de medida para el pie cuadrado (Square Feet)1. Verificar que no exista en la tabla.

    a) En el explorador de objeto posicinese sobre la tabla [Production.UnitMeasure]

    b) Presione Botn derecho y seleccionar [Script Table as] [SELECT To] [New Query Editor Window]

    c) Agregue a la consulta WHERE [UnitMeasureCode] = 'F2'd) Ejecute para comprobar que el resultado da 0 rows

    2. En nueva pantalla de editor de consultas, ejecutarINSERT INTO Production.UnitMeasureVALUES (N'F2', N'Square Feet', GETDATE())

    3. Verificar que se insert el registro apoyndose en la consulta del paso 1.

    SQL Server - Programacin USANDO TRANSACT-SQL 7

    Prof. Marlon S. Ramrez M.

    PRCTICA 2-01c: UPDATE

    Modificar el nombre a Pie Cuadrado de la nueva unidad de medida para el pie cuadrado que se cre en la prctica anterior.

    1. En nueva pantalla de editor de consultas, ejecutar

    UPDATE Production.UnitMeasure

    SET Name = N'Pie Cuadrado'

    WHERE UnitMeasureCode= 'F2'

    2. Verificar que se modific el registro apoyndose en la consulta del paso 1 de la Prctica 2-01b.

    SQL Server - Programacin USANDO TRANSACT-SQL 8

  • 10/03/2010

    5

    Prof. Marlon S. Ramrez M.

    PRCTICA 2-01d: DELETEBorrar toda la historia de costo de productos con costo estndar mayor a los 1,000.00

    1. Verificar cuantos registros tiene la tabla y cuantos tienen costos estndar mayor a 1000a) En el explorador de objeto posicinese sobre la tabla [Production.ProductCostHistory ]

    b) Presione Botn derecho y seleccionar [Script Table as] [SELECT To] [New Query Editor Window]

    c) Ejecute la consulta y anote la cantidad total de registros (395 rows).

    d) Agregue a la consulta WHERE [StandardCost ] > 1000

    e) Ejecute para comprobar los registros a borrar (aprox 50 rows).

    2. En nueva pantalla de editor de consultas, ejecutarDELETE FROM Production.ProductCostHistory

    WHERE StandardCost > 1000.00

    3. Verificar que la cantidad de registros en la tabla corresponda al total encontrado en el punto 1 menos los registros borrados en el punto 2. Apoyndose en la consulta del paso 1 (345 rows).

    4. Restaurar base de Datos AdventureWorks.bak

    SQL Server - Programacin USANDO TRANSACT-SQL 9

    Prof. Marlon S. Ramrez M.

    Formateando una Consulta Que hace la consulta?

    SELECT Production.ProductCategory.Name AS Category, Production.

    ProductSubCategory.Name AS SubCategory, Production.Product.Name AS

    ProductName ,Sales.SalesOrderHeader.OrderDate, Sales.SalesOrderDetail.

    OrderQty, Sales.SalesOrderDetail.UnitPrice

    FROM Sales.SalesOrderHeader INNER JOIN Sales.SalesOrderDetail ON

    Sales.SalesOrderHeader.SalesOrderID = Sales.SalesOrderDetail.SalesOrderID

    INNER JOIN Production.Product ON Sales.SalesOrderDetail.ProductID = Product.

    ProductID INNER JOIN Production.ProductSubCategory ON Production.Product.

    ProductSubCategoryID = Production.ProductSubCategory.ProductSubCategoryID

    INNER JOIN Production.ProductCategory ON Production.ProductSubCategory.

    ProductCategoryID = Production.ProductCategory.ProductCategoryID

    WHERE Sales.SalesOrderHeader.OrderDate BETWEEN 1/1/2003 AND 12/31/2003

    ORDER BY Production.ProductCategory.Name, Production.ProductSubCategory.Name,

    Production.Product.Name

    Una buena prctica para el programador es hacer el cdigo legible y entendible.

    SQL Server - Programacin USANDO TRANSACT-SQL 10

  • 10/03/2010

    6

    Prof. Marlon S. Ramrez M.

    Aplicando TAB a una ConsultaSELECT

    Production.ProductCategory.Name AS Category

    ,Production.ProductSubCategory.Name AS SubCategory

    ,Production.Product.Name AS ProductName

    ,Sales.SalesOrderHeader.OrderDate

    ,Sales.SalesOrderDetail.OrderQty

    ,Sales.SalesOrderDetail.UnitPrice

    FROM

    Sales.SalesOrderHeader

    INNER JOIN Sales.SalesOrderDetail

    ON Sales.SalesOrderHeader.SalesOrderID = Sales.SalesOrderDetail.SalesOrderID

    INNER JOIN Production.Product

    ON Sales.SalesOrderDetail.ProductID = Product.ProductID

    INNER JOIN Production.ProductSubCategory

    ON Production.Product.ProductSubCategoryID =

    Production.ProductSubCategory.ProductSubCategoryID

    INNER JOIN Production.ProductCategory

    ON Production.ProductSubCategory.ProductCategoryID =

    Production.ProductCategory.ProductCategoryID

    WHERE

    Sales.SalesOrderHeader.OrderDate BETWEEN 1/1/2003 AND 12/31/2003

    ORDER BY

    Production.ProductCategory.Name

    ,Production.ProductSubCategory.Name

    ,Production.Product.Name

    SQL Server - Programacin USANDO TRANSACT-SQL 11

    Prof. Marlon S. Ramrez M.

    PRCTICA 2-02: Formatear consulta con tabuladores y usando Alias para tablas

    SELECT

    PC.Name AS Category

    ,PSC.Name AS SubCategory

    ,P.Name AS ProductName

    ,SOH.OrderDate

    ,SOD.OrderQty

    ,SOD.UnitPrice

    FROM

    Sales.SalesOrderHeader AS SOH

    INNER JOIN Sales.SalesOrderDetail AS SOD

    ON SOH.SalesOrderID = SOD.SalesOrderID

    INNER JOIN Production.Product AS P

    ON SOD.ProductID = P.ProductID

    INNER JOIN Production.ProductSubcategory AS PSC

    ON P.ProductSubcategoryID = PSC.ProductSubcategoryID

    INNER JOIN Production.ProductCategory AS PC

    ON PSC.ProductCategoryID = PC.ProductCategoryID

    WHERE

    SOH.OrderDate BETWEEN 1/1/2003 AND 12/31/2003

    ORDER BY

    PC.Name

    ,PSC.Name

    ,P.Name

    SQL Server - Programacin USANDO TRANSACT-SQL 12

  • 10/03/2010

    7

    Prof. Marlon S. Ramrez M.

    Convencin de Nombres

    Por ejemplo poner los nombres de las tablas en plural y los nombres de los campos en singular.

    Usar una convencin de nombre consistente

    Incluso no utilizar espacios para evitar usar [].

    No usar caracteres especiales.

    No utilizar nombre vagos como Id

    Si dos campos de diferentes tablas contienen los mismos datos, entonces nmbrelos iguales.

    Por ejemplo utilice StudentPreferredCourses en lugar de StudPrfCrs

    Utilizar nombres que tengan significado.

    SQL Server - Programacin USANDO TRANSACT-SQL 13

    Prof. Marlon S. Ramrez M.

    Delimitando Objetos

    Se debe evitar utilizar palabras reservadas en nombres de tablas o campos.

    Si no es posible evitarlo entonces puede utilizar delimitadores.

    CREATE TABLE [Transaction]

    (TransactionId bigint NOT NULL

    ,[Timestamp] datetime NOT NULL

    ,Service varchar(75) NOT NULL

    ,[LineNo] int )

    Tambin se pueden utilizar en Transaction o Timestamp que son palabras reservadas

    SQL Server - Programacin USANDO TRANSACT-SQL 14

  • 10/03/2010

    8

    Prof. Marlon S. Ramrez M.

    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)

    ************************************************/

    Comentarios en una lnea comienzan con . Se ignora lo que esta a la derecha.

    SELECT

    PC.Name AS Category

    ,PSC.Name AS SubCategory

    ,P.Name AS ProductName

    ,SOH.OrderDate

    ,SOD.OrderQty

    -- ,SOD.UnitPrice

    FROM Sales.SalesOrderHeader AS SOH

    Existen dos botones en el SQL Management Studio para comentar y descomentar.

    SQL Server - Programacin USANDO TRANSACT-SQL 15

    Prof. Marlon S. Ramrez M.

    Las instrucciones bsicas de DDL

    Instruccin Descripcin

    CREATE Usado para crear nuevos objetos. Esto aplica a muchos objetos comunes de base de datos incluyendo base de datos, tablas, vistas, procedimientos,

    disparadores (triggers) y funciones

    ALTER Usado para modificar la estructura de un objeto existente. La sintaxis de cada objeto podra variar dependiendo de su propsito.

    DROP Usado para borrar un objeto existente. Algunos objetos no pueden ser borrados debido a que ellos pueden contener datos participando en una relacin o si otro objeto depende del objeto que se intenta borrar

    SQL Server - Programacin USANDO TRANSACT-SQL 16

  • 10/03/2010

    9

    Prof. Marlon S. Ramrez M.

    Creando una Tabla

    InstruccionesCREATE TABLE Appointment

    (

    AppointmentID int

    ,Description varchar(50)

    ,StartDateTime datetime

    ,EndDateTime datetime

    ,Resource varchar(50) NULL

    )

    PRCTICA 2-03

    1. Verificar que la tabla no exista en el explorador de objetos en la seccin [Databases]

    [AdventureWorks] [Tables]

    2. Ejecutar las instrucciones a la izquierda en el editor de consultas para crear la tabla

    3. Verificar que los objetos se crearon

    [AdventureWorks] [Tables] [dbo.Appointment] [Columns]

    SQL Server - Programacin USANDO TRANSACT-SQL 17

    Prof. Marlon S. Ramrez M.

    Creando una Vista

    InstruccionesCREATE VIEW vwProductByCategory

    AS

    SELECT

    PC.Name AS Category

    ,PSC.Name AS SubCategory

    ,P.Name AS Product

    FROM Production.ProductCategory PC

    INNER JOIN

    Production.ProductSubcategory PSC

    ON PC.ProductCategoryID =

    PSC.ProductCategoryID

    INNER JOIN Production.Product P

    ON P.ProductSubcategoryID =

    PSC.ProductSubcategoryID;

    PRCTICA 2-04

    1. Verificar que la vista no exista en el explorador de objetos en la seccin [Databases]

    [AdventureWorks] [Views]

    2. Ejecutar las instrucciones a la izquierda en el editor de consultas para crear la vista

    3. Verificar que los objetos se crearon

    [AdventureWorks] [Views] [dbo.vwProductByCategory] [Columns]

    SQL Server - Programacin USANDO TRANSACT-SQL 18

  • 10/03/2010

    10

    Prof. Marlon S. Ramrez M.

    Creando un Procedimiento Almacenado

    Instrucciones/******************************************************

    * 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()

    PRCTICA 2-051. Ejecutar las instrucciones a la izquierda en

    el editor de consultas para crear el procedimiento almacenado

    2. Leer la tabla [Production.Product] y verifique que no existe el producto AA-9999 ejecutando consultaSELECT * FROM Production.Product

    WHERE ProductNumber='AA-9999'

    3. Ejecutar el procedimiento con el siguiente comando: EXEC dbo.uspInsertOrUpdateProduct

    'Producto de Prueba', 'AA-9999', 100

    4. Ejecutar consulta a tabla [Production.Product] nuevamente y verifique que existe el producto AA-9999

    5. Apuntar el valor del campo [ProductID] ya que lo utilizar ms adelante

    SQL Server - Programacin USANDO TRANSACT-SQL 19

    Prof. Marlon S. Ramrez M.

    Creando una Funcin

    /**********************************************************

    Returns a date representing the last date

    of any given month.

    **********************************************************/

    CREATE Function dbo.fn_LastOfMonth(@TheDate datetime)

    Returns datetime

    AS

    BEGIN

    DECLARE @FirstOfMonth datetime

    DECLARE @DaysInMonth int

    DECLARE @RetDate datetime

    SET @FirstOfMonth =

    DATEADD(mm, DATEDIFF(mm,0,@TheDate), 0)

    SET @DaysInMonth =

    DATEDIFF(d, @FirstOfMonth, DATEADD(m, 1, @FirstOfMonth))

    RETURN DATEADD(d, @DaysInMonth - 1, @FirstOfMonth)

    END

    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 instruccinSELECT dbo.fn_LastOfMonth('2010-03-03')

    4. Esto mostrar la fecha representando el ltimo da de la fecha de entrada de la funcin.

    SQL Server - Programacin USANDO TRANSACT-SQL 20

  • 10/03/2010

    11

    Prof. Marlon S. Ramrez M.

    Sintaxis de Funciones DATEADD y DATEDIFF

    FuncionesDATEDIFF ( datepart , startdate , enddate )

    Regresa un entero con el resultado de la resta de enddate menos startdate. El resultado se muestra segn tipo de medida de tiempo especificado en datepart.

    DATEADD (datepart , number, date )

    A date se la suma la cantidad especificada en number segn el tipo de medida de tiempo especificado en datepart.

    startdate, enddate y date son valores del tipo time, date, smalldatetime, datetime, datetime2, o datetimeoffset. Tambin pueden ser una expresin, variable definida por usuario o una cadena de caracteres.

    number es un entero.

    Valores vlidos de datepartEn parntesis abajo los argumentos vlidos para datepart

    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)

    SQL Server - Programacin USANDO TRANSACT-SQL 21

    Prof. Marlon S. Ramrez M.

    Creando un Disparador (Trigger)

    /******************************************************

    Este es un caso ficticio para demostrar como funciona el Trigger

    Cuando un producto es actualizado UPDATE chequea si no existe

    ordenes de ventas usando el producto. Si no existe entonces no

    permite la actualizacin

    ******************************************************/

    CREATE TRIGGER tr_DelProduct ON Production.Product

    FOR UPDATE

    AS

    IF ( SELECT Count(*)

    FROM Sales.SalesOrderDetail

    INNER JOIN Deleted

    ON SalesOrderDetail.ProductID = Deleted.ProductID

    ) = 0

    BEGIN

    RAISERROR (No se puede actualizar un producto cuando no

    existe ordenes asociadas,14,1)

    ROLLBACK TRANSACTION

    RETURN

    END

    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 comandoUPDATE Production.Product

    SET Name='UNI'

    WHERE ProductID=1005

    3. El campo no sea actualiz y se muestra el siguiente mensajeMsg 50000, Level 14, State 1, Procedure tr_DelProduct, Line 16

    No se puede actualizar un producto cuando no existe ordenes asociadas

    Msg 3609, Level 16, State 1, Line 1

    The transaction ended in the trigger. The batch has been aborted.

    4. Re-leer la tabla [Production.Product] y verifique que el nombre del producto AA-9999 no ha sido modificado

    SQL Server - Programacin USANDO TRANSACT-SQL 22

  • 10/03/2010

    12

    Prof. Marlon S. Ramrez M.

    PRCTICA 2-08: Modificando Tabla

    1. Verificar las columnas de la tabla [Appointment]

    [AdventureWorks] [Tables] [dbo.Appointment] [Columns]

    2. Ejecutar las siguientes instrucciones en el editor de consultas para agregar la columna [LeadTime] a la tabla [Appointment]ALTER TABLE Appointment

    ADD LeadTime smallint NULL

    3. Verificar el cambio en el explorador de objetos

    [AdventureWorks] [Tables] [dbo.Appointment] [Columns] y botn derecho [Refresh]

    4. Ejecutar las siguientes instrucciones en el editor de consultas para eliminar la columna [Resource] de la tabla [Appointment]ALTER TABLE Appointment

    DROP COLUMN Resource

    5. Verificar el cambio en el explorador de objetos (aplicar [Refresh])

    SQL Server - Programacin USANDO TRANSACT-SQL 23

    Prof. Marlon S. Ramrez M.

    Modificando Vista

    PRCTICA 2-091. Leer la definicin de la vista

    [vwProductByCategory] siguiendo los siguientes comandos[AdventureWorks] [Views] [dbo.vwProductByCategory] + botn derecho + [Script View as] [ALTER To] [New QueryEditor Window]

    2. Hacer los cambios que sean necesarios por ejemplo agregar [, PC.ProductCategoryID] al final de los campos en la vista.

    3. Ejecutar las instrucciones4. Verificar el cambio en el explorador de

    objetos[AdventureWorks] [Views] [dbo.vwProductByCategory ] [Columns] y botn derecho [Refresh]

    InstruccionesUSE [AdventureWorks]

    GO

    /****** Object: View [dbo].[vwProductByCategory] Script Date: 03/03/2010 22:16:18 ******/

    SET ANSI_NULLS ON

    GO

    SET QUOTED_IDENTIFIER ON

    GO

    ALTER VIEW [dbo].[vwProductByCategory]

    AS

    SELECT PC.Name AS Category

    ,PSC.Name AS SubCategory

    ,P.Name AS Product

    ,PC.ProductCategoryID -- Aadido

    FROM Production.ProductCategory PC

    INNER JOIN Production.ProductSubcategory PSC

    ON PC.ProductCategoryID = PSC.ProductCategoryID

    INNER JOIN Production.Product P

    ON P.ProductSubcategoryID = PSC.ProductSubcategoryID;

    GO

    SQL Server - Programacin USANDO TRANSACT-SQL 24

  • 10/03/2010

    13

    Prof. Marlon S. Ramrez M.

    PRCTICA 2-10: Borrando Objetos

    1. Borrar todos los objetos y elementos generados en esta prctica DROP TABLE Appointment

    DROP VIEW vwProductByCategory

    DROP PROCEDURE uspInsertOrUpdateProduct

    DROP TRIGGER Production.tr_UpdProduct

    DROP FUNCTION dbo.fn_LastOfMonth

    2. Ejecutar uno a uno y verificar que halla sido borrado.

    3. Borrar registro creado en [Production].[Product] DELETEProduction.Product

    WHERE ProductNumber='AA-9999'

    SQL Server - Programacin USANDO TRANSACT-SQL 25

    Prof. Marlon S. Ramrez M.

    Lenguaje de control de datos (DCL)

    Comandos

    GRANT da permiso a una accin sobre un objeto para un usuario o rol.

    DENY restringe el permiso a una accin sobre un objeto para un usuario o rol.

    REVOKE es para remover permiso a una accin sobre un objeto.

    REVOKE puede ser utilizado para remover permisos otorgando por GRANT y DENY puede ser usado para prevenir a un principal ganar un premiso especifico a travs de un GRANT

    Estos actan sobre los siguientes objetos

    Tablas y Vistas: SELECT ,INSERT , UPDATE , and DELETE

    Procedimientos y Funciones: EXECUTE

    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

  • 10/03/2010

    14

    Prof. Marlon S. Ramrez M.

    Ejercicio 1

    1. Abrir el SSMS

    2. Seleccionar la base de datos AdventureWorkspor defecto

    3. Ejecutar las siguientes instruccionesSELECT * FROM Production.Product

    4. Revisar la barra de estado por el nmero de registros regresados por la consulta

    SQL Server - Programacin USANDO TRANSACT-SQL 27

    Prof. Marlon S. Ramrez M.

    Ejercicio 2Insertar un registro utilizando un script SQL generado1. 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 TemplateParameters+. Se abre la pantalla *Specify Values forTemplate 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