Development resources, articles, tutorials, code samples, tools and downloads for ASP.Net, SQL Server, Reporting Services, T-SQL, Windows, AWS, SAP HANA and ABAP
String Manipulation to Find Difference in Different Columns in a Wide Table
The recent thread at T-SQL forum at MSDN Dynamic SQL Stored Proc with information_schema.columns presented an interesting problem � find the differences in columns and list old and new values along with the column names in a new table.
The test tables that demonstrate the problem are:
And log table:
Now, we want to construct a SQL statement, that will populate the Log table with the Column Name and Previous and New values for this column if there is a difference.
For this purpose we will use meta-table with the information about columns Information_Schema.Columns
The query I�m using is not guaranteed to work 100% since it uses string concatenation technique and assumes that the string will be concatenated in the order of columns in a table. In my tests this technique always worked as intended.
The first script demonstrates how to list columns with differences and count number of such columns:
In the script above I used ISNULL(a.column,space(0)) <> ISNULL(b.column, space(0)) in order to account for possible NULLs in the columns. In the later scripts I will just test a.column <> b.column for simplicity.
The sample data can be displayed by running the below t-sql SELECT query.
When we execute dynamic sql script, it will compare sql data in database table z_test and find differences.
The list of different fields are listed in the output of the data compare statement as follows.
The second query shows how to create and execute script that will log column differences and previous/new values:
This generates one long insert statement for all columns with differences.
The original poster also asked for amendment in this script to do such inserts in chunks.
The next script demonstrates the same technique but with split for every 3 columns (see the difference in generated scripts in the Messages pane):
As you see, such tasks can be solved using simple string manipulation, although this technique is not guaranteed to work, especially if you try to add ORDER BY in the queries used. In my tests, though, it always worked.
Naomi Nosonovsky is a Senior Software Developer who has more than 15 years of enterprise experience in analysis, design, development and implementation of high-performance client/server data management solutions.
She is a personality of the year 2008 and 2009 at www.universalthread.com in .NET, SQL Server & VFP categories.
Naomi Nosonovsky is also an All Star contributor at ASP.NET Forums and MSDN Transact-SQL Forum.