Enforcing your data's integrity is probably the single most important issue you face when designing a database. Validating user input is one way of keeping bad data from making its way into your analyses and reports.
It takes only one piece of bad data to throw everything off. It's serious business and there are no shortcuts -- mistakes, even innocent ones, are easy to make. It's just too easy to enter one too many zeros or enter "6heodore" instead of "Theodore". Granted, you can't stop every single mistake at the input stage, but it's the best place to start. (We are working with SQL Server Express because it's free and easy to use, but the concept and examples are valid in SQL Server.)
About CHECK
When you restrict the values a column can store, you're enforcing domain integrity. In other words, you're making sure that all of the data for a single column (or a table) meets specific conditions. SQL Server offers two built-in constraints for enforcing domain integrity:
|> CHECK is a rule that applies to data. You might use a CHECK constraint to require a value for a particular field to be greater than 1 or to contain a specific number of characters.
|> DEFAULT fills in a value when the user fails to supply one. (We are not discussing DEFAULT here.)
Using CHECK to reject alpha characters
The easiest way to reject alpha characters is to use a numeric data type, but that's not always practical. Sometimes, you want a character column to contain only numeric values. This happens when valid data consists of numeric characters, but you don't use them mathematically. For instance, phone numbers and ZIP codes comprise numeric characters, but you store them as text because you won't evaluate them in mathematical equations.
A character column accepts both numbers and letters. If domain integrity requires that such a column accept only numbers, use CHECK to make that happen. It's easier than you might think. Simply specify a numeric character for each required position. A character column that stores ZIP code values is a good example.
Using Management Studio, expand a database and add a new single-column table. Name the column PostalCode and set its data type as char(5). Name the table anything you like and expand the new table's node. To add a constraint that rejects any entry that contains an alpha character, do the following:
|> Right-click the table's Constraints node and choose New Constraint.
|> Enter (PostalCode LIKE '[0-9][0-9][0-9][0-9][0-9]') in the Expression text box to limit the first five characters to numbers. (Be careful not to enter space characters between the digit component [0-9].)
|> Modify the constraint's default name to CK_PostalCodes_PostalCode.
|> Enter a description, such as "Limit ZIP code values to numbers", as shown below.
|> In the New Constraint dialog box, click Add.
|> Click Close.
|> Click Save on the Standard menu.
A simple expression rejects any alpha character
A simple expression rejects any alpha character
Now, check the constraint by trying to adding a couple of records. First, run the simple query:
USE AdventureWorks
INSERT PostalCodes
VALUES (\'40604\')
The image below shows what happens when the ZIP code value satisfies the CHECK constraint -- SQL Server adds a new record for the ZIP code value. Now, run this second query
The CHECK constraint accepts five number characters
USE AdventureWorks
INSERT PostalCodes
VALUES (\'r0604\')
The value has an alpha character -- r instead of 4 -- but the CHECK constraint catches your typo, as you can see below.
The CHECK constraint rejects any entry that contains an alpha character
The CHECK constraint rejects any entry that contains an alpha character
Add CHECK programmatically
You can add a CHECK constraint programmatically when you create the table or after by executing a Transact-SQL (T-SQL) ALTER TABLE statement. The following T-SQL adds a new column to the example table:
USE AdventureWorks
ALTER TABLE dbo.PostalCodes
ADD PostalCodeExtended char(9) NULL
GO
ALTER TABLE dbo.PostalCodes
ADD CONSTRAINT CK_PostalCodes_PostalCodeExtended
CHECK (PostalCodeExtended LIKE
\'[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]\')
GO
The first statement adds a character column named PostalCodeExtended. The next statement uses the ADD CONSTRAINT clause to add a CHECK constraint that forces number characters. The only difference is that this column expects a nine-character ZIP code value. Similarly to the manual example, the constraint will reject any value that contains an alpha character.
The image below shows what happens when you try to enter a value that's fewer than nine characters or that contains an alpha character -- the table accepts only one value, 406045555.
Both the data type and the constraint reject invalid values
You're out!
Laying siege to bad data from the get-go will reduce mistakes and the headaches later on. Defining the appropriate data type is your first line of defence. When data types aren't enough, SQL Server's CHECK constraint is a powerful ally.
If you've upgraded a legacy database that's still using rules (the predecessor to constraints), convert them to constraints. There's no guarantee that subsequent versions of SQL Server will continue to support rules. Converting rules before they're extinct will save you a lot of time and trouble later on.
To learn more about constraints visit:






1
Ralph Wilson - 13/05/08
One point that you failed to mention, though, is that, even though the developer may not have established sufficient front-end checking to have prevented the attempt to store invalid data in the database, you are still relying upon the developer to have handled the exception that will be raised when the constraint rejects the data.
In other words, there is front-end involvemnet in either case, so you need to make your developers aware of the fact that SQL Server is not going ot magically handle the bad data.
» Report offensive content
2
sushma pate - 26/05/08
i read
How do I ... reject alpha characters in a SQL Server character column?
&
coalesce function use
that is very helpful for me and very clear to understand.
» Report offensive content
3
Bert De Haes - 04/06/08
I just want to add you can have this sort of check also if you do not have a fixed number of digits. Try to add the check contraint as in this statement :
create table #tmp ( a varchar(20) not null constraint CH_tmpa check (a not like '%[^0-9]%') )
» Report offensive content
4
june Shutt - 04/06/08
What about using the Isnumeric command ?
» Report offensive content
5
Mike Miller - 04/06/08
I'm curious if there is any real advantage to storing numeric data in a text/character column. Data storage? Speed? I'm hard pressed to come up with a good case for it. Even if you don't need to perform math functions on the data, it seems that numeric columns, properly indexed, require less storage and are comparatively more efficient than text data types. Nonetheless, your article is informative and effectively covers the topic. Thanks for the posting.
» Report offensive content
6
Ray Majewski - 04/06/08
Mike, here are several reasons for using text columns for numeric text. The most important being it is really text stored in the column and not numbers. Suppose you had a postal code of 00123. A numeric column would store it as 123 and that is incorrect.
» Report offensive content
7
Ken Salins - 04/06/08
Jane - IsNumeric will return true for values like 12.45 or -37. In this example, the author only wants to accept numerals and reject the decimal point and negative sign.
» Report offensive content
8
Solomon Rutzky - 04/06/08
Although not everyone will like or accept this suggestion, more detailed CHECK constraints on character fields can be done in SQL Server 2005 (and beyond) using a CLR function for Regular Expressions. You can find many examples across many sites on how to code one of these OR you can simply download the free library of CLR functions called SQL# (SQLSharp) from: http://www.SQLSharp.com/
» Report offensive content
9
James Hutchison - 05/06/08
Hmm, as the fiirst post said the front end will need to handle the exception so why push it down to the database to handle.
» Report offensive content
10
CGreen - 05/06/08
I'm a currently involved in a project writing the front end application and the backend database. (We don't have development DBAs.) I consider it ESSENTIAL to have check constraints as a last line of defense against garbage. Besides, the front end is NOT the only way to put data in the database. Anyone with the right permissions can run a T-SQL statement and do an INSERT.
» Report offensive content
11
Thomas - 06/06/08
I guess some of you may not agree with my opinion. But I sure wont like that validation (The check constraint ) been placed on the DB. As of how I look at it its too much of a overhead to have that type of constraint on the DB.
This constraint will fire each time a character is entered and the CPU will take a bit of a beating if that type of a validation does take place. I’d rather prefer having this validation included on the UI side. So actually speaking this will be validated in three places prior to it reaching the DB server( The UI layer , Application layer , Business logic layer) .
Any thoughts !!!!!!
» Report offensive content
12
Thomas - 06/06/08
I guess some of you may not agree with my opinion. But I sure wont like that validation (The check constraint ) been placed on the DB. As of how I look at it its too much of a overhead to have that type of constraint on the DB.
This constraint will fire each time a character is entered and the CPU will take a bit of a beating if that type of a validation does take place. I’d rather prefer having this validation included on the UI side. So actually speaking this will be validated in three places prior to it reaching the DB server( The UI layer , Application layer , Business logic layer) .
Any thoughts !!!!!!
» Report offensive content
13
Jeff - 21/06/08
The data should always be validated in the database as you never know where the data is coming from. Since you could have different applications entering the data, this forces the application developers to handle the exception and force them to add thier own validation. This then cascades up to the UI. You may have multiple front ends to your applications. These should then handle any exceptions from the application layer or business logic layers. You can add the most robust validation to your UI or any layer in between and that's not going to help developer B who isn't aware of you or your UI. By adding the validation in the Database it will force future and concurrent developers to adhere to validation they may not be aware of.
» Report offensive content
14
Steve - 15/08/08
OK, I'm not a DBA. I manage the web and other DB servers but I am not a developer. I would like to see filtration of data characters at the websites that allow input to tables. But I'd also like to see the same filtration at the datafield. SQL Injection is a big deal and having more than one check at multiple points of entry is a good idea. I played with the syntax presented here but can't get results that I want.
I'm looking for a means to restrict certain data/asci characters. :, #, $, %, @, ~ from certain data fields. You see, alpha numeric would be fine for a VarChar datatype field.
Any assistance pointing me in the right direction will be appreciated.
» Report offensive content
15
Latona - 08/09/09
Good evening. Excess on occasion is exhilarating. It prevents moderation from acquiring the deadening effect of a habit. Help me! I find sites on the topic: One illegal zanpakutLT soon vented on homophobia when the right series walt whitman continued to radio.. I found only this - [URL=http://www.ismar07.org/Members/Replacement]hair Replacement orlando fl[/URL]. They tried how each gaming from the maturation had two luminaries posing the love due to shave although that became them more female, farrell hair replacement. Hair replacement cinncinati ohio: return hormone life and safe or strong disrepute dht schedule has been recommended to attempt for higher replays of fatty rates where razors are well demonstrated by newborn replacement. Thanks for the help :eek:, Latona from Kiribati.
» Report offensive content