Creación de Constraint
| 
 Los  constraints se utilizan para prevenir el registro de datos no válidos a las tablas. 
Se pueden utilizar los constraints para:
 
– Imponer reglas en los datos de una tabla cuando una fila es insertada, modificada o borrada de la tabla, el constraint se debe cumplir para que la operación se realice. 
– Previene la eliminación de una tabla si existen dependencias con otras. 
Las reglas de negocio se implementan mediante restricciones (constraints), disparadores (triggers) o código de aplicación. 
Las restricciones se almacenan en el SQL Server en las tablas syscomments, sysreferences y sysconstraints. 
La sintaxis de creación de una Tabla en SQL server es la siguiente, es posible crear una tabla con sus constraint incluidos: CREATE TABLE Tabla 
( { < definiciónColumna > 
| < restricciónTabla > } [ ,…n ]) 
< definiciónColumna > ::= { columnatipoDeDatos } 
[ [ DEFAULT expresiónConstante ] 
[ < restricciónColumna > ] [ ,..n] 
< restricciónColumna > ::= 
[ CONSTRAINT nombreRestricción ] 
| [ { PRIMARY KEY | UNIQUE } 
[ CLUSTERED | NONCLUSTERED ] ] 
| [ [ FOREIGN KEY ] 
REFERENCES tablaRef [ ( columnaRef ) ] 
[ ON DELETE { CASCADE | NO ACTION } ] 
[ ON UPDATE { CASCADE | NO ACTION } ]] 
| CHECK ( expresiónLógica ) } 
< restricciónTabla > ::= 
[ CONSTRAINT nombreRestricción ] 
{ [ { PRIMARY KEY | UNIQUE } 
[CLUSTERED | NONCLUSTERED] 
{ ( columna [ ASC | DESC ] [ ,…n ] ) } ] 
| FOREIGN KEY 
[ ( columna [ ,…n ] ) ] 
REFERENCES tablaRef [ ( columnaRef [ ,…n ] ) ] 
[ ON DELETE { CASCADE | NO ACTION } ] 
[ ON UPDATE { CASCADE | NO ACTION } ] 
| CHECK ( condicionesBúsqueda ) } 
Creación de una Tabla de Ejemplo: USE northwind 
CREATE TABLE dbo.Products 
( 
ProductID int IDENTITY (1,1) NOT NULL, 
ProductName nvarchar (40) NOT NULL, 
SupplierID int NULL, 
CategoryID int NULL, 
QuantityPerUnit nvarchar (20) NULL, 
UnitPrice money NULL CONSTRAINT DF_Products_UnitPrice DEFAULT(0), 
UnitsInStock smallint NULL CONSTRAINT DF_Products_UnitsInStock DEFAULT(0), 
UnitsOnOrder smallint NULL CONSTRAINT DF_Products_UnitsOnOrder DEFAULT(0), 
ReorderLevel smallint NULL CONSTRAINT DF_Products_ReorderLevel DEFAULT(0), 
Discontinued bit NOT NULL CONSTRAINT DF_Products_Discontinued DEFAULT(0), 
CONSTRAINT PK_Products PRIMARY KEY CLUSTERED (ProductID), 
CONSTRAINT FK_Products_Categories FOREIGN KEY (CategoryID) 
REFERENCES dbo.Categories(CategoryID) ON UPDATE CASCADE, 
CONSTRAINT FK_Products_Suppliers FOREIGN KEY (SupplierID) 
REFERENCES dbo.Suppliers(SupplierID) ON DELETE CASCADE, 
CONSTRAINT CK_Products_UnitPrice CHECK (UnitPrice >= 0), 
CONSTRAINT CK_ReorderLevel CHECK (ReorderLevel >= 0), 
CONSTRAINT CK_UnitsInStock CHECK (UnitsInStock >= 0), 
CONSTRAINT CK_UnitsOnOrder CHECK (UnitsOnOrder >= 0) 
) 
GO 
Revisión de constraint en una tabla: use northwind 
go 
sp_helpconstraint customers 
Obtener información de los Constraint a través de las tablas del sistema: Select * from information_schema.table_constraints 
Select * from information_schema.check_constraints 
Select * from information_schema.referential_constraints 
go 
Creación de Constraint: 
DROP TABLE INSTRUCTORES 
CREATE TABLE INSTRUCTORES 
(CODIGO INT IDENTITY(1,1) NOT NULL, 
NOMBRE VARCHAR(50), 
APELLIDO VARCHAR(50), 
TELEFONO VARCHAR(10) 
) 
Llave Primaria: 
ALTER TABLE INSTRUCTORES 
ADD 
CONSTRAINT PK_INSTRUCTORES PRIMARY KEY CLUSTERED (CODIGO) 
Valor Predeterminado: ALTER TABLE INSTRUCTORES 
ADD 
CONSTRAINT DF_NOMBRE DEFAULT ‘SIN NOMBRE’ 
FOR NOMBRE 
Agregar una Columna a la tabla para agregar luego un constraint: ALTER TABLE INSTRUCTORES 
ADD  NACIMIENTO SMALLDATETIME 
Restricción Check para fecha de nacimiento: ALTER TABLE INSTRUCTORES 
ADD 
CONSTRAINT CH_CUMPLEAÑOS CHECK (NACIMIENTO>=‘1995-01-01’ AND NACIMIENTO<=GETDATE()) 
Restricción Unique: ALTER TABLE INSTRUCTORES 
ADD 
CONSTRAINT U_APELLIDO UNIQUE NONCLUSTERED (APELLIDO) 
Sintaxis de una llave Foranea: [CONSTRAINT nombreRestricción] 
[FOREIGN KEY] [(columna[,…n])] 
REFERENCES tablaRef [(columnaRef [,…n])]. 
[ ON DELETE { CASCADE | NO ACTION } ] 
[ ON UPDATE { CASCADE | NO ACTION } ] 
Borrar un Constraint 
ALTER TABLE INSTRUCTORES 
DROP CONSTRAINT CH_CUMPLEAÑOS 
Para que la llave foránea y la restricción Check no comprueben los datos ya ingresados: USE Northwind 
ALTER TABLE dbo.Employees 
WITH NOCHECK————————————————->NO COMPRUEBA LOS DATOS EXISTENTES 
ADD CONSTRAINT FK_Employees_Employees 
FOREIGN KEY (ReportsTo) 
REFERENCES dbo.Employees( 
USE Northwind 
ALTER TABLE dbo.Employees 
WITH NOCHECK 
ADD CONSTRAINT FK_Employees_Employees 
FOREIGN KEY (ReportsTo) 
REFERENCES dbo.Employees(EmployeeID) 
Deshabilitar los constraint, para que los nuevos datos no se verifiquen por la restricción USE Northwind 
ALTER TABLE dbo.Employees 
NOCHECK 
CONSTRAINT FK_Employees_Employees 
USE Northwind 
ALTER TABLE dbo.Employees 
NOCHECK 
CONSTRAINT FK_Employees_Employees 
REGLAS. 
Un objeto de SQL Server son las reglas que son como constraint de tipo check, pero que pueden asociarse a mas de un campo. –CREAR UNA REGLA 
CREATE RULE AÑOS 
AS 
@NACIMIENTO>=‘1995-01-01’ AND @NACIMIENTO<=GETDATE() 
–VINCULAR LA REGLA 
EXEC sp_bindrule‘AÑOS’, ‘INSTRUCTORES.NACIMIENTO’ 
–DESVINCULAR LA REGLA 
EXEC sp_unbindrule   ‘INSTRUCTORES.NACIMIENTO’ 
–BORRAR LA REGLA 
DROP RULE AÑOS 
–VALOR DEFAULT 
CREATE DEFAULT NADA AS ‘unknown’ 
–VINCULAR EL DEFAULT 
sp_bindefault NADA, ‘INSTRUCTORES.NOMBRE’ 
–DESVINCULAR 
sp_unbindefault ‘INSTRUCTORES.NOMBRE’ 
 | 

Pingback: friv com 2014
Quanto mas coberturas, melhor para você. http://flux.theskepticalforum.com/viewtopic.php?id=7504