基于C#中的2列从数据表中删除重复行,可以通过以下步骤实现:
以下是一个示例代码,演示如何基于C#中的2列从数据表中删除重复行:
using System;
using System.Data;
using System.Data.SqlClient;
public class Program
{
public static void Main()
{
string connectionString = "YourConnectionString";
string tableName = "myTable";
string tempTableName = "tempTable";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
// Step 1: Connect to the database and select the table
string selectQuery = $"SELECT DISTINCT column1, column2 INTO {tempTableName} FROM {tableName}";
using (SqlCommand command = new SqlCommand(selectQuery, connection))
{
// Step 2: Execute the select query and store the result in a dataset
SqlDataAdapter adapter = new SqlDataAdapter(command);
DataSet dataSet = new DataSet();
adapter.Fill(dataSet);
// Step 4: Create a new temporary table
string createTempTableQuery = $"CREATE TABLE {tempTableName} (column1 VARCHAR(50), column2 VARCHAR(50))";
using (SqlCommand createTempTableCommand = new SqlCommand(createTempTableQuery, connection))
{
createTempTableCommand.ExecuteNonQuery();
}
// Step 5-6: Iterate through the dataset and insert non-duplicate rows into the temporary table
foreach (DataRow row in dataSet.Tables[0].Rows)
{
string column1Value = row["column1"].ToString();
string column2Value = row["column2"].ToString();
string insertQuery = $"INSERT INTO {tempTableName} (column1, column2) VALUES ('{column1Value}', '{column2Value}')";
using (SqlCommand insertCommand = new SqlCommand(insertQuery, connection))
{
insertCommand.ExecuteNonQuery();
}
}
// Step 7: Delete the original table and rename the temporary table
string deleteOriginalTableQuery = $"DROP TABLE {tableName}";
string renameTempTableQuery = $"EXEC sp_rename '{tempTableName}', '{tableName}'";
using (SqlCommand deleteOriginalTableCommand = new SqlCommand(deleteOriginalTableQuery, connection))
using (SqlCommand renameTempTableCommand = new SqlCommand(renameTempTableQuery, connection))
{
deleteOriginalTableCommand.ExecuteNonQuery();
renameTempTableCommand.ExecuteNonQuery();
}
}
}
}
}
请注意,上述示例代码仅供参考,实际应用中需要根据具体的数据库和表结构进行适当的修改。此外,还需要确保在连接字符串中提供正确的数据库连接信息。
领取专属 10元无门槛券
手把手带您无忧上云