The default option is to take no action. Here is an example of setting it with code: CREATE TABLE Persons
(
PersonID int PRIMARY KEY NOT NULL,
FirstName nvarchar(20),
LastName nvarchar(20) NOT NULL,
GenderID int FOREIGN KEY REFERENCES Genders(GenderID)
ON DELETE NO ACTION
);
GO
You would follow the same approach for the update. The NO ACTION option asks the database engine to issue an error if the record in the parent is deleted or updated while at least one record of the child table uses that parent record. Consider the following tables: using System;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;
public class Exercise : System.Windows.Forms.Form
{
Button btnCreateTables;
Button btnSelectRecords;
DataGridView dgvPersons;
public Exercise()
{
InitializeComponent();
}
void InitializeComponent()
{
btnCreateTables = new Button();
btnCreateTables.AutoSize = true;
btnCreateTables.Text = "Create Tables";
btnCreateTables.Location = new Point(12, 12);
btnCreateTables.Click += new EventHandler(CreateTables);
btnSelectRecords = new Button();
btnSelectRecords.AutoSize = true;
btnSelectRecords.Text = "Select Records";
btnSelectRecords.Location = new Point(120, 12);
btnSelectRecords.Click += new EventHandler(SelectRecords);
dgvPersons = new DataGridView();
dgvPersons.Location = new Point(12, 44);
dgvPersons.Size = new System.Drawing.Size(465, 145);
Controls.Add(btnCreateTables);
Controls.Add(btnSelectRecords);
Text = "People";
Controls.Add(dgvPersons);
Size = new System.Drawing.Size(500, 230);
StartPosition = FormStartPosition.CenterScreen;
dgvPersons.Anchor = AnchorStyles.Left | AnchorStyles.Top |
AnchorStyles.Right | AnchorStyles.Bottom;
}
void CreateTables(object sender, EventArgs e)
{
using (SqlConnection connection =
new SqlConnection("Data Source=(local);" +
"Database='People';" +
"Integrated Security=yes;"))
{
SqlCommand command =
new SqlCommand("CREATE TABLE Genders(" +
"GenderID int not null, " +
"Gender nvarchar(20), " +
"CONSTRAINT PK_Genders PRIMARY KEY(GenderID));",
connection);
connection.Open();
command.ExecuteNonQuery();
MessageBox.Show("A table named \"Genders\" has been created.",
"People",
MessageBoxButtons.OK,
MessageBoxIcon.Information);
}
using (SqlConnection connection =
new SqlConnection("Data Source=(local);" +
"Database='People';" +
"Integrated Security=yes;"))
{
SqlCommand command =
new SqlCommand("INSERT INTO Genders " +
"VALUES(1, 'Male'), (2, 'Female'), (3, 'Unknown');",
connection);
connection.Open();
command.ExecuteNonQuery();
MessageBox.Show("A few records have been added to the Genders table.",
"People",
MessageBoxButtons.OK,
MessageBoxIcon.Information);
}
using (SqlConnection connection =
new SqlConnection("Data Source=(local);" +
"Database='People';" +
"Integrated Security=yes;"))
{
SqlCommand command =
new SqlCommand("CREATE TABLE Persons" +
"(" +
"PersonID int PRIMARY KEY NOT NULL, " +
"FirstName nvarchar(20), " +
"LastName nvarchar(20) NOT NULL, " +
"GenderID int CONSTRAINT FK_Genders " +
" FOREIGN KEY REFERENCES Genders(GenderID) " +
" ON DELETE NO ACTION" +
");",
connection);
connection.Open();
command.ExecuteNonQuery();
MessageBox.Show("A table named \"Persons\" has been created.",
"People",
MessageBoxButtons.OK,
MessageBoxIcon.Information);
}
using (SqlConnection connection =
new SqlConnection("Data Source=(local);" +
"Database='People';" +
"Integrated Security=yes;"))
{
SqlCommand command =
new SqlCommand(
"INSERT INTO Persons(PersonID, FirstName, LastName, GenderID) " +
"VALUES(1, 'James', 'Palau', 1), " +
" (2, 'Ann', 'Nsang', 2), " +
" (3, 'Marc', 'Ulrich', 1), " +
" (4, 'Arjuh', 'Namdy', 3), " +
" (5, 'Aisha', 'Diabate', 2);",
connection);
connection.Open();
command.ExecuteNonQuery();
MessageBox.Show("A few records have been added to the Persons table.",
"People",
MessageBoxButtons.OK,
MessageBoxIcon.Information);
}
}
void SelectRecords(object sender, EventArgs e)
{
using (SqlConnection connection =
new SqlConnection("Data Source=(local);" +
"Database='People';" +
"Integrated Security=yes;"))
{
SqlCommand command =
new SqlCommand("SELECT ALL * FROM Persons;",
connection);
connection.Open();
command.ExecuteNonQuery();
SqlDataAdapter sdaPersons = new SqlDataAdapter(command);
BindingSource bsPersons = new BindingSource();
DataSet dsPersons = new DataSet("PersonsSet");
sdaPersons.Fill(dsPersons);
bsPersons.DataSource = dsPersons.Tables[0];
dgvPersons.DataSource = bsPersons;
}
}
public static int Main()
{
System.Windows.Forms.Application.Run(new Exercise());
return 0;
}
}
Here is an example of showing all records of the table:
Now, if you try to delete one of the records of the Genders table, you would receive an error. Here is an example: using System;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;
public class Exercise : System.Windows.Forms.Form
{
Button btnDeleteGender;
Button btnSelectRecords;
DataGridView dgvPersons;
public Exercise()
{
InitializeComponent();
}
void InitializeComponent()
{
btnSelectRecords = new Button();
btnSelectRecords.AutoSize = true;
btnSelectRecords.Text = "Select Records";
btnSelectRecords.Location = new Point(12, 12);
btnSelectRecords.Click += new EventHandler(SelectRecords);
btnDeleteGender = new Button();
btnDeleteGender.AutoSize = true;
btnDeleteGender.Text = "Delete Record";
btnDeleteGender.Location = new Point(120, 12);
btnDeleteGender.Click += new EventHandler(DeleteGender);
dgvPersons = new DataGridView();
dgvPersons.Location = new Point(12, 44);
dgvPersons.Size = new System.Drawing.Size(465, 145);
Controls.Add(btnSelectRecords);
Controls.Add(btnDeleteGender);
Text = "People";
Controls.Add(dgvPersons);
Size = new System.Drawing.Size(500, 230);
StartPosition = FormStartPosition.CenterScreen;
dgvPersons.Anchor = AnchorStyles.Left | AnchorStyles.Top |
AnchorStyles.Right | AnchorStyles.Bottom;
}
void SelectRecords(object sender, EventArgs e)
{
using (SqlConnection connection =
new SqlConnection("Data Source=(local);" +
"Database='People';" +
"Integrated Security=yes;"))
{
SqlCommand command =
new SqlCommand("SELECT ALL * FROM Persons;",
connection);
connection.Open();
command.ExecuteNonQuery();
SqlDataAdapter sdaPersons = new SqlDataAdapter(command);
BindingSource bsPersons = new BindingSource();
DataSet dsPersons = new DataSet("PersonsSet");
sdaPersons.Fill(dsPersons);
bsPersons.DataSource = dsPersons.Tables[0];
dgvPersons.DataSource = bsPersons;
}
}
void DeleteGender(object sender, EventArgs e)
{
using (SqlConnection connection =
new SqlConnection("Data Source=(local);" +
"Database='People';" +
"Integrated Security=yes;"))
{
SqlCommand command =
new SqlCommand("DELETE FROM Genders " +
"WHERE GenderID = 2;",
connection);
connection.Open();
command.ExecuteNonQuery();
MessageBox.Show("The second gender has been deleted.",
"People - Gender",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
public static int Main()
{
System.Windows.Forms.Application.Run(new Exercise());
return 0;
}
}
In the same way, if you had set the update to No Action, if you try updating a parent record and if the change would impact a child record, the database engine would throw an error. Here is an example: CREATE TABLE Persons
(
PersonID int PRIMARY KEY NOT NULL,
FirstName nvarchar(20),
LastName nvarchar(20) NOT NULL,
GenderID int FOREIGN KEY REFERENCES Genders(GenderID)
ON DELETE NO ACTION
ON UPDATE NO ACTION
);
The cascade option indicates that, if something happens to a record in the parent table, the child records receive the change. For example, if you are using the Delete Rule, if a record is deleted in the parent table and if some records in the child table use the value in the parent table, those records in the child table get deleted. To apply it programmatically, add CASCADE after ON DELETE or ON UPDATE. Here is an example: CREATE TABLE Persons
(
PersonID int PRIMARY KEY NOT NULL,
FirstName nvarchar(20),
LastName nvarchar(20) NOT NULL,
GenderID int FOREIGN KEY REFERENCES Genders(GenderID)
ON DELETE CASCADE
);
GO
INSERT INTO Persons(PersonID, FirstName, LastName, GenderID)
VALUES(1, N'James', N'Palau', 1),
(2, N'Ann', N'Nsang', 2),
(3, N'Marc', N'Ulrich', 1),
(4, N'Arjuh', N'Namdy', 3),
(5, N'Aisha', N'Diabate', 2);
GO
If you apply the cascade option to the Update Rule, when a record of the parent table is changed, the child records receive the change.
Instead of displaying a nasty error or even deleting records on cascade when something happens to a record of a parent table, probably a better option is to reset to NULL every record of the child table if that record is related to the parent table. To set it programmatically, after ON DELETE or ON UPDATE, add SET NULL. Here is an example: DROP TABLE Persons;
GO
DROP TABLE Genders;
GO
CREATE TABLE Genders
(
GenderID int not null,
Gender nvarchar(20),
CONSTRAINT PK_Genders PRIMARY KEY(GenderID)
);
GO
INSERT INTO Genders
VALUES(1, N'Male'), (2, N'Female'), (3, N'Unknown');
GO
CREATE TABLE Persons
(
PersonID int PRIMARY KEY NOT NULL,
FirstName nvarchar(20),
LastName nvarchar(20) NOT NULL,
GenderID int FOREIGN KEY REFERENCES Genders(GenderID)
ON DELETE SET NULL
);
GO
INSERT INTO Persons(PersonID, FirstName, LastName, GenderID)
VALUES(1, N'James', N'Palau', 1),
(2, N'Ann', N'Nsang', 2),
(3, N'Marc', N'Ulrich', 1),
(4, N'Arjuh', N'Namdy', 3),
(5, N'Aisha', N'Diabate', 2);
GO
The update follows the same logic: If a record of the parent table is updated, any record in the child table and that gets its value from the parent table would have its value set to NULL.
If a column of a parent table has a default value, when a record of that column is affected by some action, you can ask the database engine to apply the default value to the related records of the child table. To do this programmatically, use ON DELETE SET DEFAULT or ON UPDATE SET DEFAULT. Here is an example: CREATE TABLE Persons
(
PersonID int PRIMARY KEY NOT NULL,
FirstName nvarchar(20),
LastName nvarchar(20) NOT NULL,
GenderID int default 3
CONSTRAINT FK_Genders FOREIGN KEY REFERENCES Genders(GenderID)
ON DELETE SET DEFAULT
);
GO
INSERT INTO Persons(PersonID, FirstName, LastName, GenderID)
VALUES(1, N'James', N'Palau', 1),
(2, N'Ann', N'Nsang', 2),
(3, N'Marc', N'Ulrich', 1),
(4, N'Arjuh', N'Namdy', NULL),
(5, N'Aisha', N'Diabate', 2);
GO
If you decide to delete a table, first check if it involves in a relationship. If a table is a child, you can easily delete it using any of the techniques we know already. If a table is a parent, you will receive an error. Consider the following two tables CREATE TABLE Genders
(
GenderID int not null PRIMARY KEY,
Gender nvarchar(20)
);
GO
CREATE TABLE Persons
(
PersonID int PRIMARY KEY NOT NULL,
FirstName nvarchar(20),
LastName nvarchar(20) NOT NULL,
GenderID int FOREIGN KEY REFERENCES Genders(GenderID)
);
GO
INSERT INTO Genders
VALUES(1, N'Make'), (2, N'Female'), (3, N'Unknown');
GO
INSERT INTO Persons(PersonID, FirstName, LastName, GenderID)
VALUES(1, N'Peter', N'Mukoko', 1), (2, N'Ann', N'Nsang', 2);
GO
If you try to delete the Genders table, which is a parent to the Persons, table, you would receive an error. To avoid this problem (this error), you can first delete the child table.
After creating a table or when inheriting a table created by someone else, you may find out that it lacks a primary key. You can add it, of course following some rules. You have two options. Imagine you have the following table: CREATE TABLE Employees
(
FirstName nvarchar(20),
LastName nvarchar(20),
DepartmentCode nchar(6)
);
You can add the PRIMARY KEY expresion after defining the new column. Here is an example: ALTER TABLE Employees
ADD EmployeeNumber int not null PRIMARY KEY;
As an alternative, you can add a column, and then use the CONSTRAINT formula to define the primary key. Here is an example: ALTER TABLE Employees
ADD EmployeeNumber int not null
CONSTRAINT PK_Employees PRIMARY KEY(EmployeeNumber);
Just as you add a primary key to an already created table, you can also add a new column that is a foreign key. Consider the following table named Persons: CREATE TABLE Genders
(
GenderID int not null PRIMARY KEY,
Gender nvarchar(20)
);
CREATE TABLE Persons
(
PersonID int PRIMARY KEY NOT NULL,
FirstName nvarchar(20),
LastName nvarchar(20) NOT NULL
);
The formula to add a foreign key to an existing table is: ALTER TABLE TableName
ADD NewColumnName DataType Options
FOREIGN KEY REFERENCES ParentTableName(ColumnNameOfOtherTable);
Here is an example of adding a foreign key to the above Persons table: ALTER TABLE Persons ADD GenderID int NULL FOREIGN KEY REFERENCES Genders(GenderID);
When performing data entry, in some columns, even after indicating the types of values you expect the user to provide for a certain column, you may want to restrict a range of values that are allowed. In the same way, you can create a rule that must be respected on a combination of columns before the record can be created. For example, you can ask the database engine to check that at least one of two columns received a value. For example, on a table that holds information about customers, you can ask the database engine to check that, for each record, either the phone number or the email address of the customer is entered. The ability to verify that one or more rules are respected on a table is called a check constraint. A check constraint is a Boolean operation performed by the SQL interpreter. The interpreter examines a value that has just been provided for a column. If the value is appropriate:
If the value is not appropriate:
You create a check constraint at the time you are creating a table.
To create a check constraint in SQL, first create the column on which the constraint will apply. Before the closing parenthesis of the table definition, use the following formula: CONSTRAINT name CHECK (expression) The CONSTRAINT and the CHECK keywords are required. As an object, make sure you provide a name for it. Inside the parentheses that follow the CHECK operator, enter the expression that will be applied. Here is an example that will make sure that the hourly salary specified for an employee is greater than 12.50: using System;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;
public class Exercise : System.Windows.Forms.Form
{
Button btnCreateTable;
public Exercise()
{
InitializeComponent();
}
void InitializeComponent()
{
btnCreateTable = new Button();
btnCreateTable.AutoSize = true;
btnCreateTable.Text = "Select Records";
btnCreateTable.Location = new Point(12, 12);
btnCreateTable.Click += new EventHandler(CreateTable);
Text = "Kolo Bank";
Controls.Add(btnCreateTable);
}
void CreateTable(object sender, EventArgs e)
{
using (SqlConnection connection =
new SqlConnection("Data Source=(local);" +
"Database='Exercise2';" +
"Integrated Security=yes;"))
{
SqlCommand command =
new SqlCommand("CREATE TABLE Employees(" +
"[Employee Number] nchar(7)," +
"[Full Name] varchar(80)," +
"[Hourly Salary] smallmoney," +
"CONSTRAINT CK_HourlySalary CHECK ([Hourly Salary] > 12.50));",
connection);
connection.Open();
command.ExecuteNonQuery();
MessageBox.Show("A table named Employees has been deleted.",
"Exercise",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
public static int Main()
{
System.Windows.Forms.Application.Run(new Exercise());
return 0;
}
}
It is important to understand that a check constraint is neither an expression nor a function. A check constraint contains an expression and may contain a function as part of its definition. With the constraint(s) in place, during data entry, if the user (or your code) provides an invalid value, an error would display. Instead of an expression that uses only the regular operators, you can use a function to assist in the checking process. You can create and use your own function or you can use one of the built-in Transact-SQL functions. |
|
|||||||||||||||||||||||
|
|