SQL Comparison SDK
Latest version: 10.0
Knowledge Base
Executing your own SQL queries together with SDK synchronization
Category: How do I?
Date: 03 Feb 2011
Product: SQL Comparison SDK
When executing a synchronization script created by the SQL Comparison SDK, it may be desired that some ad-hoc queries be intermixed with the SQL produced by the Red Gate APIs.
Because the BlockExecutor class can only run SQL code by converting ExecutionBlocks to SQL code and submitting them to the SQL Server, custom SQL cannot be introduced into the query stream. It is possible, however, to break an ExecutionBlock into individual query batches and running them using the .NET Framework's ADO .NET methods.
In the following C# example, a SQL query "SET LANGUAGE us_english" needs to be submitted before the synchronization produced by the SQL Data Compare Engine. First, a connection is made to the server using the connection properties of the second database. Then a transaction is created. The custom SQL query is run first, then each batch of SQL from the ExecutionBlock in order. Finally, the transaction is committed. If any errors occur during the execution of the SQL script, then the error is written to the console and the transaction will be rolled back.
- [C#]
- using System;
- using RedGate.SQLCompare.Engine;
- using System.IO;
- using RedGate.Shared.SQL.ExecutionBlock;
- using System.Data.SqlClient;
- namespace CompareTwoDatabases
- {
- /// <summary>
- /// Demonstration that compares the WidgetStaging database to the WidgetProduction database
- /// and synchronizes them using the ADO .NET libraries
- /// </summary>
- class Program
- {
- static void Main(string[] args)
- {
- using (Database widgetStaging = new Database(),
- widgetProduction = new Database())
- {
- // Retrieve the schema information for the two databases
- widgetStaging.Register(new ConnectionProperties(".", "WidgetStaging"), Options.Default);
- widgetProduction.Register(new ConnectionProperties(".", "WidgetProduction"), Options.Default);
- // Compare widgetStaging to widgetProduction. Comparing in this order makes WidgetProduction the second database
- Differences stagingVsProduction = widgetStaging.CompareWith(widgetProduction, Options.Default);
- // Select the differences to include in the synchronization. In this case, we're using all differences.
- foreach (Difference difference in stagingVsProduction)
- {
- difference.Selected = true;
- }
- Work work = new Work();
- // Create the migration without the transactional bits --
- //we will let ADO .NET manage the transactions using SqlTransaction
- // The script is to be run on WidgetProduction so the runOnTwo parameter is true
- work.BuildFromDifferences(stagingVsProduction, Options.Default | Options.NoSQLPlumbing, true);
- // We can now access the messages and warnings
- Console.WriteLine("Messages:");
- foreach (Message message in work.Messages)
- {
- Console.WriteLine(message.Text);
- }
- Console.WriteLine("Warnings:");
- foreach (Message message in work.Warnings)
- {
- Console.WriteLine(message.Text);
- }
- // Disposing the execution block when it's not needed any more is important to ensure
- // that all the temporary files are cleaned up
- using (ExecutionBlock block = work.ExecutionBlock)
- {
- // Display the SQL used to synchronize
- Console.WriteLine("SQL to synchronize:");
- Console.WriteLine(block.GetString());
- // Make a connection string from the second database connection properties (runOnTwo)
- System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection("Data Source=" + widgetProduction.ConnectionProperties.ServerName + ";Initial Catalog=" + widgetProduction.ConnectionProperties.DatabaseName + ";Integrated Security=SSPI");
- System.Data.SqlClient.SqlCommand cmd = conn.CreateCommand();
- conn.Open();
- SqlTransaction trans = conn.BeginTransaction("MyTransaction");
- cmd.Transaction = trans;
- //Run the first command
- cmd.CommandText = "SET LANGUAGE us_english";
- cmd.ExecuteNonQuery();
- //Run batches
- for (int i = 0; i < block.batchcount;="">
- {
- Batch b = block.GetBatch(i);
- try
- {
- if (!b.Marker) //Do not run blocks that are simply "GO"
- {
- cmd.CommandText = b.Contents;
- cmd.ExecuteNonQuery();
- }
- }
- catch (System.Data.SqlClient.SqlException se)
- {
- Console.WriteLine("Execute SQL failed: " + se.Message);
- trans.Rollback();
- }
- }
- trans.Commit();
- }
- Console.WriteLine("Press [Enter]");
- Console.ReadLine();
- }
- }
- }
- }
- [/C#]
Document ID: KB200809000297 Keywords: SQL,SDK,custom,SQL,ADO,command
Was this article helpful?
SQL Comparison SDK
- Licenses.licx is not a valid Win32 application
- Application licensing invalidated by renaming assembly
- Excluding a table from a data comparison
- Manually licensing Red Gate assemblies
- RedGate.Licensing.Helper.dll is attempting managed execution inside OS Loader lock
- Troubleshooting SQL Comparison SDK licensing
- SQL Compare synchronization error 'Full-Text Search is not installed'
- Using SQL Data Compare mappings in projects using the API
- Licensing automated builds with NAnt
- Licensing ASP .NET applications
- Running SQL code inside SQL Comparison SDK applications
- Creating an HTML report of schema differences in C#
- Creating a synchronization script without batch markers
- Creating an HTML report of schema differences in Visual Basic .NET
- SQL Toolkit has become SQL Comparison SDK
- SQL Comparison SDK column mapping
- Executing your own SQL queries together with SDK synchronization
- Error 1603 occurring during installation
- Licensing SDK applications in Visual Studio 2010
all SQL products
- Compatibility of Red Gate tools in 64-bit environments
- Application has encountered an error and needs to close
- Error message after installing SQL Toolbelt - The description for Event ID ( 1 ) in Source ( nview_info ) cannot be found.
- Changing the temporary directory used by the installer
- Toolbelt Installer "hanging" while "scanning volumes"
- Login failing with "trusted SQL Server connection" error when using RunAs
all products
- Some Red Gate products identified as containing a trojan by Anti-Virus software
- Activation may fail with Unknown Error -1
- Product uses web help although a CHM file is available locally
- Argument exception resulting from missing environment variable
- Check for updates may fail when used through proxies
- 'Unidentified Publisher' error when repairing or uninstalling
- Licensing activates product as standard edition
- Moving Red Gate software products to another machine
- Red Gate tools log locations
- The application UI opening slowly when there is no internet access
SQL Comparison SDK
all SQL products
all products
- Red Gate product acknowledgements
- Activating your products
- Activating your products
- Red Gate bundle history
- Check for updates
- Troubleshooting Check for Updates errors
- Current versions
- Deactivating your products
- Installing Red Gate products from the .msi file
- Requesting additional activations
- Serial numbers for bundles
- Reactivating using a different serial number
- Extending your trial
- Finding your serial numbers
- Moving a serial number from one computer to another
- No response received for manual activation
- Licensing and activation resources
- Licensing and activation resources
- Troubleshooting licensing and activation errors
- Licensing and activation FAQs
- Red Gate tools log file locations
- Download old versions of products
- Download product prerequisites & utilities
- Support & upgrades
- Upgrading your software
- Upgrading FAQs

Licensing and distribution