Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to del a SQLServer record relationed with onother one in same tabl

Status
Not open for further replies.

polocar

Programmer
Sep 20, 2004
89
IT
Hi,
I’m writing a program in Visual C# 2005 Professional Edition.
This program connects to a SQL Server 2005 database called “Generations” (in which there is only one table, called “Generations”), and it allows the user to add, edit and delete the various records of the table.
“Generations” table has the following fields:
“IDPerson”, NamePerson”, “AgePerson” and “IDParent”.
A record contains the information about a person (his name, his age and the ID of his parent).
The “IDPerson” and “IDParent” fields are connected with a PRIMARY – FOREIGN KEY constraint (I attach below the T-SQL Query that creates the database with the table, the fields and the inner constraint):

Code:
USE master
GO
--DROP Database Generations;  (insert this statement only if “Generations” database doesn’t exist yet)
--GO  (insert this statement only if “Generations” database doesn’t exist yet)
CREATE DATABASE Generations
GO
USE Generations
GO
CREATE TABLE Generations (IDPerson int IDENTITY (1,1) PRIMARY KEY, NamePerson nvarchar(50) NOT NULL, AgePerson int NOT NULL,IDParent int NULL FOREIGN KEY REFERENCES Generations(IDPerson));
INSERT INTO Generations (NamePerson, AgePerson, IDParent) VALUES ('Paul', 97, NULL);
INSERT INTO Generations (NamePerson, AgePerson, IDParent) VALUES ('Henry', 74, 1);
INSERT INTO Generations (NamePerson, AgePerson, IDParent) VALUES ('Bob', 51, 2);
INSERT INTO Generations (NamePerson, AgePerson, IDParent) VALUES ('Mike', 25, 3);
INSERT INTO Generations (NamePerson, AgePerson, IDParent) VALUES ('John', 78, NULL);
INSERT INTO Generations (NamePerson, AgePerson, IDParent) VALUES ('Peter', 47, 5);
INSERT INTO Generations (NamePerson, AgePerson, IDParent) VALUES ('Patrick', 25, 6);
INSERT INTO Generations (NamePerson, AgePerson, IDParent) VALUES ('Michael', 2, 7);
INSERT INTO Generations (NamePerson, AgePerson, IDParent) VALUES ('Jim', 65, NULL);
INSERT INTO Generations (NamePerson, AgePerson, IDParent) VALUES ('Justin', 40, 9);

At this point I have created a very simple C# program to view the fields’ values of every record in a Form.
So, I have inserted a “txtIDPerson”, “txtNamePerson”, “txtAgePerson” and “txtIDParent” TextBox objects, and a “btnPrevoiusPerson”, “btnNextPerson”, “btnAddPerson”, “btnEditPerson”, “btnDeletePerson”, “btnOk” and “btnCancel” Button objects (I think the names explain clearly their function).
I have written the code that imports the database structure and data in the offline ADO.NET objects (included the relationship between “IDPerson” and “IDParent” fields).

The issue that I don’t solve is an error that raises when I try to delete a person that has sons (in other words, a record with one or more records descending).
For example, if I try to delete “Paul” (who has Henry as son, Bob as grandchild and Mike as great-grandchild), the compiler gives the following error:

“The DELETE statement is in conflict with SAME TABLE REFERENCE “FK__Generatio__IDPar_7D78A4E7”. The conflict has occurred in “dbo.Generations” table, column ‘IDParent’ of “Generations” database”.

If I try to delete Mike (who has no sons), there are no problems.

The last thing I have noticed is that, if in the T-SQL statement I create the “Generations” table without the “IDPerson” – “IDParent” constraint (but I leave it unchanged in the C# code), everything functions correctly: if I try to delete Paul, the program deletes Paul, Henry, Bob and Mike.

As I need to keep the constraint in the SQL Server database too (not only in the C# code), do you know if there is a way to make it function? (is it a bug of SQL Server 2005, or the bug is me?)

I attach the C# code below, if there is anyone who wants to test it (of course you must connect to your own SQL Server 2005 instance where you have created “Generations” with the T-SQL code, so you have to customize the cn.ConnectionString C# statement. The T-SQL code for the database creation and population is attached above).

Thank you very much

Code:
using System;
using System.Collections;
using System.Data;
using System.Data.OleDb;
using System.Data.Common;
using System.Data.SqlClient;
using System.Drawing;
using System.Windows.Forms;

class SeparateMain
{
    public static void Main()
    {
        Application.Run(new Generations());
    }
}
class Generations: Form
{
	/**************************************************************************/
	/*            CREAZIONE CONTROLLI PRESENTI NEL FORM                       */
	/**************************************************************************/

    // SQL Server database objects
    public SqlConnection cn;
    public SqlDataAdapter daGenerations;
    public DataSet dsTablesSet;
    public DataTable dtGenerations;
    public CurrencyManager cmGenerations;

    // Graphical objects (Labels, TextBoxes and Buttons)
    public Label lblIDPerson, lblNamePerson, lblAgePerson, lblIDParent;
    public TextBox txtIDPerson, txtNamePerson, txtAgePerson, txtIDParent;
    public Button btnPreviousPerson, btnNextPerson, btnAddPerson, btnEditPerson, btnDeletePerson, btnOk, btnCancel, btnClose;


	public Generations()
	{
        // Form dimension and position
        Size = new System.Drawing.Size(570, 300);
        Text = "Generations";
        CenterToScreen();

        // SQL Server objects istantiation and initialization
        cn = new SqlConnection();
        daGenerations = new SqlDataAdapter();
        dsTablesSet = new DataSet();
        dtGenerations = new DataTable();

        dsTablesSet.DataSetName = "TablesSet";

        // Table "Generations"
        dtGenerations.TableName = "Generations";

        dtGenerations.Columns.Add("IDPerson", typeof(int));
        dtGenerations.Columns["IDPerson"].AutoIncrement = true;
        dtGenerations.Columns["IDPerson"].AutoIncrementSeed = 1;
        dtGenerations.Columns["IDPerson"].AutoIncrementStep = 1;

        dtGenerations.Columns.Add("NamePerson", typeof(string));
        dtGenerations.Columns["NamePerson"].AllowDBNull = false;
        dtGenerations.Columns["NamePerson"].DefaultValue = "";

        dtGenerations.Columns.Add("AgePerson", typeof(int));
        dtGenerations.Columns["AgePerson"].AllowDBNull = false;

        dtGenerations.Columns.Add("IDParent", typeof(int));

        dtGenerations.PrimaryKey = new DataColumn[] { dtGenerations.Columns["IDPerson"] };

        dsTablesSet.Tables.Add(dtGenerations);

        // "Generations" inner relation
        dsTablesSet.Relations.Add("Generations_ParentSon", dtGenerations.Columns["IDPerson"], dtGenerations.Columns["IDParent"]);

        cn.ConnectionString = "Persist Security Info=False;Integrated Security=SSPI;database=Generations;server=(local)\\TECLOGICA;Connect Timeout=10";

        string strSQL;
        SqlParameterCollection pc;
        SqlParameter param;

        // "Generations" UPDATE, INSERT, DELETE logic
        strSQL = "SELECT IDPerson, NamePerson, AgePerson, IDParent FROM Generations ORDER BY IDPerson";
        daGenerations.SelectCommand = new SqlCommand(strSQL, cn);

        strSQL = "UPDATE Generations SET NamePerson = @NamePerson_New, AgePerson = @AgePerson_New, IDParent = @IDParent_New WHERE IDPerson = @IDPerson_Orig";
        daGenerations.UpdateCommand = new SqlCommand(strSQL, cn);
        pc = daGenerations.UpdateCommand.Parameters;

        pc.Add("@NamePerson_New", SqlDbType.NVarChar, 50, "NamePerson");
        pc.Add("@AgePerson_New", SqlDbType.Int, 0, "AgePerson");
        pc.Add("@IDParent_New", SqlDbType.Int, 0, "IDParent");

        param = pc.Add("@IDPerson_Orig", SqlDbType.Int, 0, "IDPerson");
        param.SourceVersion = DataRowVersion.Original;

        strSQL = "SET IDENTITY_INSERT Generations ON; INSERT INTO Generations (IDPerson, NamePerson, AgePerson, IDParent) VALUES (@IDPerson, @NamePerson, @IDParent); SET IDENTITY_INSERT Generations OFF";
        daGenerations.InsertCommand = new SqlCommand(strSQL, cn);
        pc = daGenerations.InsertCommand.Parameters;
        pc.Add("@IDPerson", SqlDbType.Int, 0, "IDPerson");
        pc.Add("@NamePerson", SqlDbType.NVarChar, 50, "NamePerson");
        pc.Add("@AgePerson", SqlDbType.Int, 0, "AgePerson");
        pc.Add("@IDParent", SqlDbType.Int, 0, "IDParent");

        strSQL = "DELETE FROM Generations WHERE IDPerson = @IDPerson";
        daGenerations.DeleteCommand = new SqlCommand(strSQL, cn);
        pc = daGenerations.DeleteCommand.Parameters;
        pc.Add("@IDPerson", SqlDbType.Int, 0, "IDPerson");

        daGenerations.Fill(dsTablesSet, "Generations");

        // Initialize CurrencyManager object
        cmGenerations = (CurrencyManager)BindingContext[dsTablesSet, "Generations"];

        // Graphical objects istantiation and initialization 
        lblIDPerson = new Label();
        lblIDPerson.Parent = this;
        lblIDPerson.Size = new Size(120, 25);
        lblIDPerson.Location = new Point(10, 10);
        lblIDPerson.Text = "ID";

        txtIDPerson = new TextBox();
        txtIDPerson.Parent = this;
        txtIDPerson.Size = new Size(120, 25);
        txtIDPerson.Location = new Point(lblIDPerson.Left, lblIDPerson.Bottom);
        txtIDPerson.Enabled = false;
        txtIDPerson.DataBindings.Add("Text", dsTablesSet, "Generations.IDPerson");

        lblNamePerson = new Label();
        lblNamePerson.Parent = this;
        lblNamePerson.Size = new Size(120, 25);
        lblNamePerson.Location = new Point(lblIDPerson.Right + 20, lblIDPerson.Top);
        lblNamePerson.Text = "Name";

        txtNamePerson = new TextBox();
        txtNamePerson.Parent = this;
        txtNamePerson.Size = new Size(120, 25);
        txtNamePerson.Location = new Point(lblNamePerson.Left, lblNamePerson.Bottom);
        txtNamePerson.Enabled = false;
        txtNamePerson.DataBindings.Add("Text", dsTablesSet, "Generations.NamePerson");

        lblAgePerson = new Label();
        lblAgePerson.Parent = this;
        lblAgePerson.Size = new Size(120, 25);
        lblAgePerson.Location = new Point(lblNamePerson.Right + 20, lblNamePerson.Top);
        lblAgePerson.Text = "Age";

        txtAgePerson = new TextBox();
        txtAgePerson.Parent = this;
        txtAgePerson.Size = new Size(120, 25);
        txtAgePerson.Location = new Point(lblAgePerson.Left, lblAgePerson.Bottom);
        txtAgePerson.Enabled = false;
        txtAgePerson.DataBindings.Add("Text", dsTablesSet, "Generations.AgePerson");

        lblIDParent = new Label();
        lblIDParent.Parent = this;
        lblIDParent.Size = new Size(120, 25);
        lblIDParent.Location = new Point(lblAgePerson.Right + 20, lblAgePerson.Top);
        lblIDParent.Text = "IDParent";

        txtIDParent = new TextBox();
        txtIDParent.Parent = this;
        txtIDParent.Size = new Size(120, 25);
        txtIDParent.Location = new Point(lblIDParent.Left, lblIDParent.Bottom);
        txtIDParent.Enabled = false;
        txtIDParent.DataBindings.Add("Text", dsTablesSet, "Generations.IDParent");

        btnPreviousPerson = new Button();
        btnPreviousPerson.Parent = this;
        btnPreviousPerson.Size = new Size(120, 25);
        btnPreviousPerson.Location = new Point(150, 100);
        btnPreviousPerson.Text = "Previous";
        btnPreviousPerson.Click += new EventHandler(btnPreviousPerson_Click);

        btnNextPerson = new Button();
        btnNextPerson.Parent = this;
        btnNextPerson.Size = new Size(120, 25);
        btnNextPerson.Location = new Point(btnPreviousPerson.Right + 20, btnPreviousPerson.Top);
        btnNextPerson.Text = "Next";
        btnNextPerson.Click += new EventHandler(btnNextPerson_Click);

        btnAddPerson = new Button();
        btnAddPerson.Parent = this;
        btnAddPerson.Size = new Size(120, 25);
        btnAddPerson.Location = new Point(80, 160);
        btnAddPerson.Text = "Add";
        btnAddPerson.Click += new EventHandler(btnAddPerson_Click);

        btnEditPerson = new Button();
        btnEditPerson.Parent = this;
        btnEditPerson.Size = new Size(120, 25);
        btnEditPerson.Location = new Point(btnAddPerson.Right + 20, btnAddPerson.Top);
        btnEditPerson.Text = "Edit";
        btnEditPerson.Click += new EventHandler(btnEditPerson_Click);

        btnDeletePerson = new Button();
        btnDeletePerson.Parent = this;
        btnDeletePerson.Size = new Size(120, 25);
        btnDeletePerson.Location = new Point(btnEditPerson.Right + 20, btnEditPerson.Top);
        btnDeletePerson.Text = "Delete";
        btnDeletePerson.Click += new EventHandler(btnDeletePerson_Click);

        btnOk = new Button();
        btnOk.Parent = this;
        btnOk.Size = new Size(120, 25);
        btnOk.Location = new Point(150, 220);
        btnOk.Text = "OK";
        btnOk.Visible = false;
        btnOk.Click += new EventHandler(btnOk_Click);

        btnCancel = new Button();
        btnCancel.Parent = this;
        btnCancel.Size = new Size(120, 25);
        btnCancel.Location = new Point(btnOk.Right + 20, btnOk.Top);
        btnCancel.Text = "Cancel";
        btnCancel.Visible = false;
        btnCancel.Click += new EventHandler(btnCancel_Click);

        btnClose = new Button();
        btnClose.Parent = this;
        btnClose.Size = new Size(120, 25);
        btnClose.Location = new Point(420, 220);
        btnClose.Text = "Close";
        btnClose.Click += new EventHandler(btnClose_Click);
    }

    void btnAddPerson_Click(object sender, EventArgs e)
    {
        cmGenerations.AddNew();

        txtNamePerson.Enabled = true;
        txtIDParent.Enabled = true;

        btnPreviousPerson.Visible = false;
        btnNextPerson.Visible = false;
        btnAddPerson.Visible = false;
        btnEditPerson.Visible = false;
        btnDeletePerson.Visible = false;

        btnOk.Visible = true;
        btnCancel.Visible = true;
    }

    void btnEditPerson_Click(object sender, EventArgs e)
    {
        txtNamePerson.Enabled = true;
        txtIDParent.Enabled = true;

        btnPreviousPerson.Visible = false;
        btnNextPerson.Visible = false;
        btnAddPerson.Visible = false;
        btnEditPerson.Visible = false;
        btnDeletePerson.Visible = false;

        btnOk.Visible = true;
        btnCancel.Visible = true;
    }

    void btnDeletePerson_Click(object sender, EventArgs e)
    {
        cmGenerations.RemoveAt(cmGenerations.Position);
        daGenerations.Update(dtGenerations);
    }

    void btnPreviousPerson_Click(object sender, EventArgs e)
    {
        if (cmGenerations.Position > 0)
            cmGenerations.Position--;
    }

    void btnNextPerson_Click(object sender, EventArgs e)
    {
        if (cmGenerations.Position < cmGenerations.Count-1)
            cmGenerations.Position++;
    }

    void btnOk_Click(object sender, EventArgs e)
    {
        cmGenerations.EndCurrentEdit();
        daGenerations.Update(dtGenerations);

        txtNamePerson.Enabled = false;
        txtIDParent.Enabled = false;

        btnOk.Visible = false;
        btnCancel.Visible = false;

        btnPreviousPerson.Visible = true;
        btnNextPerson.Visible = true;
        btnAddPerson.Visible = true;
        btnEditPerson.Visible = true;
        btnDeletePerson.Visible = true;
    }

    void btnCancel_Click(object sender, EventArgs e)
    {
        cmGenerations.CancelCurrentEdit();

        txtNamePerson.Enabled = false;
        txtIDParent.Enabled = false;

        btnOk.Visible = false;
        btnCancel.Visible = false;

        btnPreviousPerson.Visible = true;
        btnNextPerson.Visible = true;
        btnAddPerson.Visible = true;
        btnEditPerson.Visible = true;
        btnDeletePerson.Visible = true;
    }

    void btnClose_Click(object sender, EventArgs e)
    {
        Close();
    }
}
 
Try updating the foreign key column to a null or a reserved record. That will break the inter-record dependency so that you can delete them for real.

Chip H.


____________________________________________________________________
If you want to get the best response to a question, please read FAQ222-2244 first
 
It's not a bug in anything, that is how it is supposed to work.

If you must keep the constaint on the table, then adjust your code to delete the children before the parent.

If you dont need to have the constraint on the table, then take it off and keep your code as is.
 
Don't delete a person. I would NEVER do that. Keep the record in the table, have a flag that indicates active record. If the record is deleted, throw the flag and don't act like it is active any more.

But actual deletion of records is not always the best way to go in this type of situation.

If you must delete, run a query first that finds if they have children and then assigns those children to another entity (a holding pen for reassignment perhaps) so that the person can be deleted in peace.

----------------------------------------

TWljcm8kb2Z0J3MgIzEgRmFuIQ==
 
Hi guys,
thanks for your answers.
As I must delete, in the code I have inserted a message box that asks the user, during the procedure of deleting a person, if he wants to delete also the descending records (click Yes), or if he wants to delete only that record and to mantain its descending ones in the table (click No).
In case 1 (delete also the descending records), there is a recursive function that, before deleting the selected record, it deletes its descending ones.
In case 2 (delete only that record), there is a simple function that sets to DBNull.Value the "IDParent" field of the descending records.
In this way the program functions correctly.

Thank you very much
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top