You are on page 1of 3

Check Constraints

Check constraints creation statements were also created previously using the following TSQL:

1  

2 SELECT @Sql_Command = '

3 USE [' + @Database_Name + '];

4 SELECT

5 schemas.name AS Schema_Name,

6 tables.name AS Table_Name,

7 ''ALTER TABLE ['' + schemas.name + ''].['' + tables.name + '']

8 WITH '' + CASE WHEN check_constraints.is_not_trusted = 1 THEN ''NOCHECK'' ELSE ''CHECK'' END + '' ADD

CONSTRAINT ['' + check_constraints.name + '']


9

CHECK '' + check_constraints.definition


10

FROM sys.check_constraints
11

INNER JOIN sys.tables


12

ON tables.object_id = check_constraints.parent_object_id
13

INNER JOIN sys.schemas


14

ON tables.schema_id = schemas.schema_id';
15

IF @Schema_Name IS NOT NULL


16

BEGIN
17

SELECT @Sql_Command = @Sql_Command + '


18

WHERE schemas.name = ''' + @Schema_Name + '''';


19

END
20

IF @Table_Name IS NOT NULL AND @Schema_Name IS NOT NULL


21

BEGIN
22 SELECT @Sql_Command = @Sql_Command + '

23 AND tables.name = ''' + @Table_Name + '''';

24 END

25 IF @Table_Name IS NOT NULL AND @Schema_Name IS NULL

26 BEGIN

27 SELECT @Sql_Command = @Sql_Command + '

28 WHERE tables.name = ''' + @Table_Name + '''';

29 END

30  

31 INSERT INTO @Check_Constraints

32 (Schema_Name, Table_Name, Check_Constraint_Definition)

33 EXEC sp_executesql @Sql_Command;

34  

While no column lists were needed for this work, we did need to verify if a constraint was created
with the NOCHOCK attribute. Otherwise, the creation statement is relatively simple. Optional
filters on schema and table help reduce the data returned to include only what we are interested
in based on the stored proc parameters. Once we have the creation script, we can script out the
check constraints as follows:

1  

2 IF EXISTS (SELECT * FROM @Check_Constraints WHERE Schema_Name = @Schema_Name_Current AND

Table_Name = @Table_Name_Current)
3

BEGIN
4

SELECT
5

@Schema_Build_Text = @Schema_Build_Text + '


6

 
7

' + Check_Constraint_Definition + '


8 GO'

9 FROM @Check_Constraints

10 WHERE Schema_Name = @Schema_Name_Current

11 AND Table_Name = @Table_Name_Current;

12 END

13  

If any check constraints exist, then add the previously-created scripts to our growing table
creation script.

You might also like