Published on

October 9, 2011

Identifying and Removing Bad Records in SQL Server

As database administrators and developers, we often encounter situations where data needs to have certain required elements in order to be processed correctly. In a large dataset, there may be incomplete or incorrect records that cannot be processed. In this article, we will explore how to use Common Table Expressions (CTEs) and the OUTPUT clause in SQL Server to identify and remove bad records.

Scenario

Let’s consider a scenario where a company receives data from vendors about musicians available to perform at music events. The data is received in a specific format in a flat file. If the flat file doesn’t contain the rate quote for a specific musician, then the entire record for that musician is considered bad and needs to be sent back to the vendor for correction. Only complete records are sent to the company’s management team for approval.

The goal is to identify the bad records and remove them from the dataset. We will use the table “dbo.Test_Table” to store the vendor data and the table “dbo.Test_Table_Bad_Records” to store the identified bad records.

Identifying and Removing Bad Records

To identify and remove the bad records, we will use a combination of CTEs and the OUTPUT clause. The process involves the following steps:

  1. Create the table “dbo.Test_Table_Bad_Records” to store the bad records.
  2. Use a CTE to find the starting row of each record for a musician.
  3. Use another CTE to find the ending row of each bad record.
  4. Join the two CTEs to find the range of rows for each bad record.
  5. Delete the rows falling within the range of each bad record from the “dbo.Test_Table” table.
  6. Use the OUTPUT clause to insert the deleted bad records into the “dbo.Test_Table_Bad_Records” table.

By following these steps, we can effectively identify and remove the bad records from the dataset.

Conclusion

Using CTEs and the OUTPUT clause in SQL Server can greatly simplify the process of identifying and removing bad records from a dataset. By leveraging these features, we can efficiently process large sets of data and ensure that only complete and accurate records are used for further analysis or processing.

In the next article, we will explore how to use recursive CTEs to solve another T-SQL puzzle. Stay tuned!

Click to rate this post!
[Total: 0 Average: 0]

Let's work together

Send us a message or book free introductory meeting with us using button below.