SQLDataAdapter查询返回重复行问题求助
Hey Chris, let's dig into why you're seeing duplicate rows in your DataTable even though your database only has 4 unique records. Since the source data is clean, the issue is almost certainly in your code or query logic—here are the top things to check:
You're calling
Fill()multiple times without clearing the DataTable
This is the most common culprit. TheSqlDataAdapter.Fill()method appends rows to your existing DataTable by default, instead of overwriting them. If you accidentally runFill()twice (say, in a loop, or after an initial test call), you'll end up with 8 rows total (the original 4 duplicated).
Example of the problematic code:DataTable myTable = new DataTable(); myAdapter.Fill(myTable); // First fill: 4 rows // ... some other code ... myAdapter.Fill(myTable); // Second fill: now 8 rows (duplicates)Fix: Either call
myTable.Clear()before eachFill(), or make sure you only invokeFill()once for the DataTable.Your SQL query is returning duplicate rows
Even if your base table has no duplicates, a poorly constructed query can introduce them. Double-check your SELECT statement:- Are you using a
JOINwith another table that has multiple matching records per row? For example, joining a customer table to an orders table where one customer has multiple orders would return duplicate customer rows. - Did you accidentally use a
CROSS JOIN(which returns all possible combinations of rows from two tables)? - Are there any
GROUP BYorDISTINCTclauses missing that would collapse duplicate results?
Test your query directly in your database management tool (like SSMS for SQL Server) to confirm it returns exactly 4 unique rows.
- Are you using a
Missing primary key on the DataTable
While this doesn't usually cause duplicates during the initialFill(), it can lead to unexpected duplicates if you're performing subsequent operations like merging data or updating rows. If your DataTable doesn't have a primary key defined, the adapter can't identify existing rows to update—so it might append duplicates instead of overwriting.
Fix: After filling the DataTable, set its primary key using the schema from your database:myTable.PrimaryKey = new DataColumn[] { myTable.Columns["YourPrimaryKeyColumn"] };Incorrect
MissingSchemaActionsetting
If you've modified theMissingSchemaActionproperty of your SqlDataAdapter, double-check it's set appropriately. For example,MissingSchemaAction.AddWithKeyensures that primary key information is imported from the database, which helps the adapter handle rows correctly. If this is set toMissingSchemaAction.Addinstead, the adapter might not recognize unique rows properly in edge cases.
Start with checking for multiple Fill() calls and testing your SQL query directly—those two fixes resolve 90% of these kinds of issues. Let me know if you find the root cause!
内容的提问来源于stack exchange,提问作者Chris F

