Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (12.19 KB, 4 trang )
2.5 Define Defaults and Constraints
One of the main concepts to keep in mind when you're creating databases is that you need
to provide a means to keep garbage (bad data) out of your tables. Default values make
sure that each new record begins with valid data. An example of this is if you want to
make sure that a date is entered for the order date of an invoice. You could set up a
default value of today's date for new records.
Constraints allow you to specify what business rules you want to use with your tables,
such as if you want to allow dates that are entered into the Order Date field to come after
today's date. This How-To explains how to use defaults and constraints to their full
potential and how to create them in Visual Studio .NET.
You have started down the path of handling your business rules by creating tables and
setting the data types of the columns in the tables. You have even set up relationships
between tables. Now you want to make life easier for your users and suggest what values
they could use, and more importantly, what values are acceptable. How do you do this by
defining defaults and constraints?
Technique
By using default values, you can guide your users and save them time. For example,
perhaps you have a mailing list application, and the user is entering addresses. If the
majority of the entries are from Washington (or WA), then you could set the default
property of the State field to be WA.
Check constraints, not to be confused with the constraint type of index, allow you to
create validation clauses that can control data that goes into the tables. An example of this
would be if you didn't want someone from California (CA) entered into the addresses
table from the last paragraph. You could then enter a constraint check that would read
something like State <> 'CA'.
Note
The rest of this chapter will use the Northwind database because it has a
great structure that makes it easy to show how to use necessary
techniques.