Great Ideas. Always Flowing.

We are not happy until you are happy. Client satisfaction guaranteed. Whatever your needs and requirements, we have the skills and resources for the job!

Popular Posts

Tags

2008 2008 Express Add AFTER alert Alias Aliases Alter Alternating And ASC Assist BETA Blog Cancel Check ON Checkbox Checkbox Group Color Column Columns Combo Box Composite Confirm Confirm Message Control CREATE CREATE TABLE Data Data Springs Database DDL DELETE Delete Confirm Demo Demonstration DESC Direct Access DNN DotNetNuke Drop Drop Constratint Drop Down Drop Down List DS Dynamic Dynamic Blog Dynamic Forms Dynamic Registration Dynamic Views Edit Event Example Express Fade In Fade Out Field Filters FK Forms Full-Table Scan Generating Generator Generators Great Ideas Group Help HTML Increase Index Indexes Input Integrity jQuery Label Listbox Listener Message Modify My Account MySQL No NULL Often Ok ON Optimization Optimize Option Options Oracle Order By Perform Performance PK Popup PostreSQL Queries Query QuestionOptionValue Radio Button Radio Button Group References referential Round Script Search Search Filters SearchOption SearchOptionValue Select Server Snippet Sort Springs SQL SQL Driven SQL Driven Query SQL Express SQL Server SQL Server 2005 SQL Server 2008 SQL Server 2008 Express SQL Server 2008 R2 SQL Server Express SSMS Stored Stored Procedure TABLE Tables Temporary Tool Tools Tooltip Tooltips Transact-SQL Trials Triggers TSQL T-SQL Unique UPDATE Use Useful Views Widget Widgets Window Yes [userimage] 10 64 bit Ability ABS Action Active Forums Alleviate Alternating Colors Alternating Rows Analytics ARB asp.net asp.net validation AuthARB Authorize.NET Avoid Back Button Basecamp Blog Blog Posts Blogging Browser Browser Back Browser Close Browser History Browser Script Button cascading style sheet Case Char Character CharAt CharAt() Check chip levinson Click client side validation Close Browser Close Window Collection 5.0 Comment Compatibility Compatible Completion completion event Confirm Message Conform Constraints content localization Count Timer Countdown CRM css csv Cursor Custom Custom HTML Custom JavaScript Custom JavaScript File customer feedback Customize Data Data Integrity Data Springs Data Springs Blog Data Springs Collection Data Springs Development Data Springs Planning Data Springs Training Databases DataSprings Date Time JavaScript Debug Info default value Delete Demonstration DF DNN DNN Authentication DNN Blog DNN Core Profile Property dnn html module dnn modules dnn schedule error dnn schedule multiple DNN Store document document.getElementById DotNetNuke dotnetnuke 5.4.4 DotNetNuke Analytics DotNetNuke Forums DotNetNuke JavaScript DotNetNuke Modules dotnetnuke reporting dotnetnuke scheduler dotnetnuke user image Double Double Quotes DR DROP Drop Constraint DropDown Login DS dynamic Dynamic Data dynamic fields Dynamic Form Dynamic Forms dynamic forms silent post Dynamic Forms Tutorial dynamic login Dynamic PDF Form Completion Event dynamic registration dynamic registration silent post dynamic registration user image dynamic user directory dynamic views DynamicRegistration_Question DynamicRegistration_QuestionResponse email email issues Encapsulated Encapsulation Even Event Event Viewer Example Excel Execute Export Export to Excel Facebook Facebook Connect Field FieldID First FirstName Fix Foreign Key Form Form Post Formatting Forms Forum Flow Full Table Scan Fully Function Google Analytics Google Analytics Ecommerce Great Great ideas Grid guides hidden field Hide Show Rows Highrise Highrise API Hourly Services HTML HTTP Post iDeal IE IE 10 Image Image Button Include Inconsistancy Info Information Injection INSERT Integration Interactive User Import Interface internet Internet Explorer iPAD iPAD App for Highrise iPAD Highrise App Items JavaScript JavaScript hide show JS Function Layout Lead Generation Learn Left Left Quote Link LinkedIn list import Live Blog localization Log Logic Login login module login skin object Loop Mandeeps Match Message Microsoft Live Writer module configuration Modules Monthly Services Name Netherlands New News Blog NL NOT NULL oAuth2 Odd OnClick Open Web Studio opt in email OWS Part 1 Part 2 Passed payment gateway paypal Phone Number Placement Post Postback Posts Premium Integration Premium Services Premium Support Primary Key Procedure Products profile Quarterly Services Question question fields Question Loop Question Value QuestionOption Quick Quotes Recommend Recommendation Recurring Billing Redirect Referential Integrity registration Rendered Replace replace html text report views reports Resolution Resource resource files resx Retrieve Retrieving Right Right Quote Rows Ryan Bakerink Sales Force SalesForce Script Scripting Scripts Sequential Access server side validation Silent Post Single Single Quotes Single Sign On skin object Snowcovered Solution sp Springs SQL sql 2005 pivot sql default value SQL Example sql import SQL Injection sql query sql replace statement sql reports SQL Server sql server 2005 SSL SSO stored stored procedure String style sheet stylesheet Submit Submit Button Submit Image Submit Link success story Suggest Suggestion Support Syntax Table technical techwise research Temp test credit card numbers testimonial Text/HTML thumbnail image Time Timer Tip Token Topic Transaction Trial Trigger TSQL T-SQL Tutorial Twitter Types of Constraints Unique Update Highrise user user directory user profile image users online Variable View Web Based Work Around writer writing xls xlsx XML

In the Flow

rss

Data Springs, Inc. - An online diary and web log from staff and customers for premium DotNetNuke resources, Data Springs Modules, and Data Springs Services.


SQL Server Constraints

Getting Started:

Constraints are rules assigned to columns in your SQL tables. The main use of a Constraint is to help ensure that data integrity measures are met. Data integrity is very important. The whole idea of Data Integrity is to maintain a consistency of data. Constraints assist with Data Integrity, referential integrity(Primary Keys and Foreign Keys), and aids Normalization for your Database tables.

Data Integrity:

Lets say that we have a SQL table named “Contacts” and one of the columns in this table is “PhoneNumber”. Now when you think of storing a phone number, there’s many formats that come to mind:

  1. (xxx) xxx – xxxx
  2. xxx-xxx-xxxx
  3. xxxxxxxxxx

Data Integrity is ensuring that you pick a format for “Phone Numbers” and stick to that format.  You would be violating Data Integrity if you chose to store format #1, #2 and #3 into the PhoneNumber column of the Contacts Table.

 

Types of Constraints:

On SQL Server, there are many types of Constraints that you can utilize. Below are the most commonly used:

  • PRIMARY KEY
  • FOREIGN KEY
  • UNIQUE
  • NOT NULL
  • CHECK

Using “PRIMARY KEY” Constraint:

The Primary Key Constraint, enforces that a column value must be unique and specifies the column as the Primary Key.

Example of Creating a Primary key on a CREATE TABLE statement:
-----------------------------------------------

CREATE TABLE TableName
(
[ID] INT IDENTITY(1,1) PRIMARY KEY,
[Column1] NVARCHAR(200),
[Column2] NVARCHAR(200)
)

-----------------------------------------------

You can add a Primary Key Constraint to an existing table:
-----------------------------------------------

ALTER TABLE TableName
ADD CONSTRAINT Give_Constraint_a_Name PRIMARY KEY(ColumnName)

-----------------------------------------------

Using “FOREIGN KEY” Constraint:

The Foreign Key Constraint allows you to specify that a column in your table is the Primary key to another table, thus granting you linking access to the other table via the value in this column. This promotes referential integrity, meaning that you're making your SQL Table a dependent to another table(Child of Parent).

I’ve created a simple example, there are two tables “Table1” and “Table2”":
-----------------------------------------------

/*Parent Table */

CREATE TABLE Table1
(
[Table1ID] INT IDENTITY(1,1) PRIMARY KEY,
[Column1] NVARCHAR(200),
[Column2] NVARCHAR(200),
[Column3] NVARCHAR(200)
)

/*Dependent Table */

CREATE TABLE Table2
(
[Table2ID] INT IDENTITY(1,1) PRIMARY KEY,
[Table1ID] INT FOREIGN KEY REFERENCES Table1 (Table1ID),
[Column1] NVARCHAR(200),
[Column2] NVARCHAR(200),
[Column3] NVARCHAR(200)
)

-----------------------------------------------

NOTE: By adding a FOREIGN KEY constraint to your table. Consider the following:

  • You can’t add a record to Table2 unless a record exists in Table1 and the Table1ID matches in both tables.
  • You must delete a record from Table1 then Table2. You can’t delete from Table2 and then Table1.

 

You can add a FOREIGN KEY constraint to an existing table with the following syntax:
----------------------------------------------- 
ALTER TABLE Table2
ADD CONSTRAINT Name_of_Constraint FOREIGN KEY (Table1ID) REFERENCES Table1 (Table1ID)
 
-----------------------------------------------

 

Using “UNIQUE” Constraint: 

The Unique Constraint ensures that a column will contain a Unique Value:
-----------------------------------------------

CREATE TABLE TableName
(
[Table2ID] INT IDENTITY(1,1) PRIMARY KEY,
[Column1] NVARCHAR(200) UNIQUE,
[Column2] NVARCHAR(200),
[Column3] NVARCHAR(200)
)


-----------------------------------------------

 

As you can see I’ve used the UNIQUE Constraint on the [Column1] column on Table1. This is specifying that all Column1 values must be unique/different. If you attempt to INSERT a record with a value for Column1 which already exists in a record of Table1, then you will receive an error. 

UNIQUE Constraints - Although functioning like a Primary Key Constraint, the difference is that you can apply this to multiple columnsand this constraint means that not a single value can be replicated in this column. This type of column could be used for Social Security Numbers, Credit Card Numbers, email addresses, etc.. The difference is that Primary key is used as the column to link other tables together via referential integrity. Unique doesn't carry this responsibility, even though it could.

You can add a UNIQUE Constraint to an existing table:


-----------------------------------------------
 ALTER TABLE TableName
ADD CONSTRAINT Name_of_Constraint UNIQUE (Column1)


-----------------------------------------------

 

Using “NOT NULL” Constraint:

The NOT NULL Constraint enforces that a value must exist and cannot contain "NULL" / unknown. Below is an example:
-----------------------------------------------

CREATE TABLE TableName
(
[Table2ID] INT IDENTITY(1,1) PRIMARY KEY,
[Column1] NVARCHAR(200) NOT NULL,
[Column2] NVARCHAR(200) NOT NULL,
[Column3] NVARCHAR(200) NOT NULL
)


-----------------------------------------------

You can add this constraint to columns in an existing table:
-----------------------------------------------

ALTER TABLE TableName
ALTER COLUMN [Column1] NVARCHAR(200) NOT NULL


-----------------------------------------------

 

Using “CHECK” Constraint:

The CHECK CONSTRAINT allows you to verify that a value is met for a column. This assists by restricting any unwanted values in a column:
-----------------------------------------------

CREATE TABLE Table1
(
[Table2ID] int identity(1,1) PRIMARY KEY,
[Column1] nvarchar(200),
[Column2] nvarchar(200),
[Column3] money,
CONSTRAINT Name_of_Constraint CHECK ([Column3] >= 0.00)
)


-----------------------------------------------

You can add a CHECK Constraint to check for multiple values:
-----------------------------------------------

CREATE TABLE TableName
(
[Table2ID] int identity(1,1) PRIMARY KEY,
[Column1] nvarchar(200),
[Column2] nvarchar(200),
[Column3] money,
CONSTRAINT Name_of_Constraint CHECK ([Column2] = 'Single', 'Married', 'Divorced')
)


-----------------------------------------------

NOTE: That when adding a CHECK Constraint accepting multiple  values as demonstrated above, the value you’re inserting into [Column2] must match the values in the Constraint(‘Single’, ‘Married’, ‘Divorced’), or else you’ll receive an error and the INSERT will fail.

You can add a CHECK Constraint to a column in an existing table:
-----------------------------------------------

ALTER TABLE TableName
ADD CONSTRAINT Name_of_Constraint CHECK ([Column3] > 0.00)


-----------------------------------------------

 

DROPPING CONSTRAINTS:

The syntax to drop a constraint is in the following manner:
-----------------------------------------------

ALTER TABLE Table1
DROP CONSTRAINT Name_of_Constraint


-----------------------------------------------

 

IMPORTANT NOTES FOR REFERENTIAL CONSTRAINTS: USING THE RIGHT ORDER:

  • You must define a Primary Key constraint on a column before using a Foreign Key constraint on that column in another table.
  • When dropping a table or removing constraints you must do so in the right order. Foreign key first, Primary key after.



Comments are closed.

Recent Comments

 
 

Join our mailing list...

Get current news and events the easy way
 
 
   
Subscribe Me

Recent Blogs...

 
Copyright 2005 - 2011 by Data Springs, Inc.