In writing a database system, the easiest and safest way to ensure data consistency in the system is to establish a foreign key constraint in the DBMS. However, if the foreign key constraint is violated when deleting the primary key data, although the DBMS will give an error message, for example, the prompt message "% 1! Statement and % 2! % 3! Constraint '% 4! 'Conflicted. This conflict occurred in database '% 6! ', Table' % 8! '% 10! % 11! % 13 !.", However, these prompts are unfriendly to end users, so they write a class to detect foreign key conflicts when deleting records. The Code is as follows:
Using System;
Using System. Data;
Using System. Data. SqlClient;
Using Microsoft. ApplicationBlocks. Data;
Namespace DataAccess. SQLServerDAL
{
///
/// Summary of Check.
///
Public class Check
{
///
/// DBMS
///
Const string DEFAULT_SYSTABLES = "systables ";
# Region CkeckFKBeginDelete
///
/// Check whether a foreign key conflict exists before deleting the record.
///
/// Object
/// Name of the table to be deleted
/// Primary key value of the record to be deleted
/// Error message returned
/// True-no conflict, false-conflict exists
Public bool CkeckFKBeginDelete (SqlTransaction trans, string tableName, string id, ref string errText)
{
String selectString; // SQL query statement
String fkTableName; // Foreign key table name
String fkColumnName; // Foreign key column name
Object obj; // the return value of the SQL query.
String description; // meaning of the foreign key table
Int count; // number of records that reference the primary key in the foreign key table
String [] tableNames = {"sysforeignkeys "};
DataSet ds = BuildDataTables ();
// Retrieve all the foreign key tables of this table
SelectString = "SELECT fkeyid, fkey FROM sysforeignkeys a, sysobjects B WHERE a. rkeyid = B. id AND B. name = @ name ";