简体   繁体   中英

How do I go about fixing my database table after inserting a list of records different id's corresponding to same name

I insert a list of records into sql and I want the ID to correspond to only 1 specific name but in this case I want to make it so that if a name is used by 2 different ids I can forcefully override that id and change it's value to whichever ID has the lower number. I don't know if this is clear or not but I can give an example. I want it so that when the programme sees Adam also having NameID 2 it changes its ID to 1. I am programming in c# but even pseudocode would help I am just struggling with incorporating c# logic and sql querys.

Records:

NameID:1 Name: Adam

NameID:2 Name: Adam

NameID:3 Name: Sarah

I tried to see if a primary key has been used and used a data reader to confirm if it has rows.Then I look to see if the name has also been used before with a select statement and data reader but I don't know how to go from there I am trying to understand how to query sql with csharp logic. If anyone could help me I would really appreciate it this concept has had me stuck quite a lot.

Well, we assume you have a primary key, but as suggested by others, such a opeeration would be better done in sql studio.

However, you can code this, and say somthing like this:

string strSQL =
    $@"select firstName, count(*) as NameCount,
    (SELECT MIN(t.Nameid) from People as T where t.Firstname = People.Firstname)
    as LowNameID
    FROM People
    group by people.Firstname
    having count(*) > 1";

using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
    using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
    {
        conn.Open();
        DataTable rstDuplicates = new DataTable();
        rstDuplicates.Load(cmdSQL.ExecuteReader());

        // process duplicates, set ones with higher number = same as lowest
        cmdSQL.CommandText =
            @"update People Set NameID = @NameID where FirstName = @FName
                AND NameID <> @NameID";

        cmdSQL.Parameters.Add("@NameID", SqlDbType.Int);
        cmdSQL.Parameters.Add("@FName", SqlDbType.NVarChar);

        foreach (DataRow OneName in rstDuplicates.Rows)
        {
            cmdSQL.Parameters["@NameID"].Value = OneName["LowNameID"];
            cmdSQL.Parameters["@FName"].Value = OneName["FirstName"];
            cmdSQL.ExecuteNonQuery();
        }
    }
}

I would consider fixing up this mess. I would suggest deleting the duplicated reocrds, and setup the code to NOT allow the same name (if that is your goal here). In other words, don't allow such additions if that is your goal in the first place.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM