Check constraint and Like condition
Check Constraints
This
SQL Server tutorial explains how to use the check constraints in
SQL Server (Transact-SQL) with syntax and examples.
Note
- A
check constraint can NOT be defined on a SQL View.
- The
check constraint defined on a table must refer to only columns in that
table. It can not refer to columns in other tables.
- A
check constraint can NOT include a Subquery.
- A
check constraint can be defined in either a CREATE TABLE
statement or
a ALTER TABLE
statement.
Create
Check
CREATE TABLE nremployees1
( employee_id INT NOT NULL,
last_name VARCHAR(50) NOT NULL,
first_name VARCHAR(50),
salary INT,
CONSTRAINT NRCHECK
CHECK (salary > 500)
);
Using
money datatype
CREATE TABLE employees( employee_id INT NOT NULL, last_name VARCHAR(50) NOT NULL, first_name VARCHAR(50), salary MONEY, CONSTRAINT check_salary CHECK (salary > 0));Alter check constraint
ALTER TABLE nrdata
ADD CONSTRAINT checksal
CHECK (sal > 500);
Drop conatraint
ALTER TABLE nrdata
DROP CONSTRAINT checksal;
Disable a Check Constraint
ALTER TABLE nrdata
NOCHECK CONSTRAINT checksal;
Enable a Check Constraint
ALTER TABLE nrdata
WITH CHECK CHECK CONSTRAINT checksal;
SQL Server Conditions
|
2 or more conditions to be met |
|
|
Any one of the conditions are met |
|
|
Combine AND and OR conditions |
|
|
Use wildcards in a WHERE clause |
|
|
Alternative to multiple OR conditions |
|
|
Negate a condition |
|
|
Test for a NULL value |
|
|
Test for a NOT NULL value |
|
|
Retrieve within a range (inclusive) |
|
|
Condition is met if subquery returns at least one row |
SELECT *FROM employeesWHERE last_name LIKE 'B%';
SELECT *FROM employeesWHERE last_name LIKE '%o%';
SELECT *FROM employeesWHERE first_name LIKE 'Ad_m';This SQL Server LIKE condition example would return all
employees whose first_name is
4 characters long, where the first two characters is 'Ad' and the last
character is 'm'. For example, it could return employees whose first_name is
'Adam', 'Adem', 'Adim', 'Adom', 'Adum', etc.
SELECT *FROM employeesWHERE employee_number LIKE '123_';You might find that you are looking for an employee_number, but
you only have 3 of the 4 digits. The example above, would retrieve potentially
10 records back (where the missing value could equal anything from 0 to 9). For
example, it could return employees whose employee numbers are:
1230, 1231, 1232, 1233, 1234, 1235, 1236, 1237, 1238, 1239
Comments
Post a Comment