Thursday, February 6, 2014

How to script a SQL Server database object using xSQL Schema SDK

Using the xSQL Schema Compare SDK it is very easy to generate the CREATE, DROP and ALTER (when alter is supported) scripts for any database object. The following example shows how to generate the CREATE script for the table Employees from the AdventureWorks database:

using xSQL.Schema.Core;
using xSQL.Schema.SqlServer;
using xSQL.SchemaCompare.SqlServer;

namespace xSQL.Sdk.SchemaCompare.Examples
{
    class Scripting
    {
        /// <summary>

        /// This method reads the schema of the database AdventureWorks and scripts the table Employee.
        /// </summary>
        public static void Script()
        {
            SqlServer server;
            SqlDatabase database;
            SqlTable table;
            ScriptingOptions options;
            try
            {
                //--create the SQL Server object

                server = new SqlServer(@"(local)");

                //--create the database object

                database = server.GetDatabase("AdventureWorks");

                //--attach an event handler to database.SchemaOperation event in order to get progress information during the schema read

                database.SchemaOperation += new EventHandler<SchemaOperationEventArgs>(database_SchemaOperation);

                //--read the database schema

                database.ReadSchema();

                //--create scripting options;

                options = new ScriptingOptions();
                options.CreateScript = true;
                options.DropScript = false;
                options.AlterScript = false;

                //--locate and script the Employee table

                table = database.SqlTables["HumanResources", "Employee"];
                if (table != null)
                    Console.Write(table.GetScript(options));
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }

        private static void database_SchemaOperation(object sender, SchemaOperationEventArgs e)
        {
            //--exclude verbose messages

            if (e.Message.MessageType != OperationMessageTypeEnum.Verbose)
                Console.WriteLine(e.Message.Text);
        }
    }
}

Tuesday, February 4, 2014

Step by step - compare and sync two sql database schemas in your .NET app using xSQL SDK

Step 1: reference the three namespaces required by xSQL Schema Compare SDK
      using xSQL.Schema.Core;
      using xSQL.Schema.SqlServer;
      using xSQL.SchemaCompare.SqlServer;


Step 2: Create the SqlServer objects for the left and right SQL Server
      SqlServer xServer, yServer;
      // create the left SQL Server object - let's assume you are using Windows authentication

      xServer = new SqlServer(@"(local)\LeftServer");
      // create the right SQL Server - let's assume you are using SQL Server authentication

      yServer = new SqlServer(@"(local)\RightServer", "<user>", "<password>");

Step 3: Create database objects for the two databases being compared
      SqlDatabase xDatabase, yDatabase;
      // create the left database

      xDatabase = xServer.GetDatabase("Source");
      // create the right database

      yDatabase = yServer.GetDatabase("Target");

Step 4: Create the schema comparer object
      SqlSchemaCompare comparer;
      comparer = new SqlSchemaCompare(xDatabase, yDatabase);


Step 5: (optional) Change the comparison options if you need to
      comparer.Options.CompareUsers = false;
      comparer.Options.CompareSchemas = false;
      comparer.Options.CompareDatabaseRoles = false;
      comparer.Options.CompareApplicationRoles = false;


Step 6: (optional/recommended) it is a good practice to attach event handlers to some of the schema events in order to get progress information during the comparison.
      comparer.LeftDatabase.SchemaOperation += new EventHandler<SchemaOperationEventArgs>(database_SchemaOperation);
      comparer.RightDatabase.SchemaOperation += new EventHandler<SchemaOperationEventArgs>(database_SchemaOperation);
      comparer.SchemaOperation += new EventHandler<SchemaOperationEventArgs>(database_SchemaOperation);


      private static void database_SchemaOperation(object sender, SchemaOperationEventArgs e)
      {
            //--exclude verbose messages             if (e.Message.MessageType != OperationMessageTypeEnum.Verbose)
                  Console.WriteLine(e.Message.Text);
      }


Step 7: Compare the schemas of the two databases
      // step 1: read the schema
      comparer.ReadSchema();

      // step 2: pair the database objects

      comparer.PairObjects();

      // step 3: compare the database schema

      comparer.Compare();

      // check for errors that could have occurred during the schema compare.

      // some errors are handled quietly and do not stop the process; those that are critical throw exceptions
      // quiet errors are collected and stored into the ErrorRepository object
      if (ErrorRepository.Instance.HasErrors())
      {
            Console.WriteLine("Some errors occurred during the database compare");
            Console.Write(ErrorRepository.Instance.GetErrors());
      }

      // check the database status; exit if no schema differences are found.

      if (comparer.SqlDatabasePair.ComparisonStatus == ComparisonStatusEnum.Equal)
            return;


Step 8: Generate the synchronization script for the target database and execute it (let's assume here that the right database is the target - you can substitute left for right if the left database is your target)
      // get the T-SQL script intended for the right database; that is the script that should be executed
      // on Target database to make it the same as the Source database
      sqlScript = comparer.GetRightDatabaseScript();
      if (!sqlScript.IsEmpty())
      {
            // print the synchronization log

            Console.Write(sqlScript.GetLog());
            // print the synchronization script

            Console.Write(sqlScript.GetScript());
            // attach event handlers to ScriptManager object to get some progress info during the script execution

            sqlScript.SchemaScriptExecuting += new EventHandler<SchemaScriptEventArgs>(sqlScript_SchemaScriptExecuting);
            // execute the sync script

            status = sqlScript.Execute();
            // check the execution and print any errors

            if (status == ScriptExecutionStatusEnum.Succeeded)
            {
                  Console.WriteLine("Database synchronization finished successfully");
            }
            else if (status == ScriptExecutionStatusEnum.Canceled)
            {
                  Console.WriteLine("Database synchronization was canceled");
            }
            else
            {
                  // check for errors

                  if (ErrorRepository.Instance.HasErrors())
                  {
                        Console.WriteLine("Some errors occurred during the script execution");
                        Console.Write(ErrorRepository.Instance.GetErrors());
                  }
            }
      }

      private static void sqlScript_SchemaScriptExecuting(object sender, SchemaScriptEventArgs e)
      {
            Console.WriteLine("{0} {1}", DateTime.Now.ToString("HH:mm:ss"), e.Script);
      }


Step 9: Catching exception. All exceptions are listed here for clarity, but you can reduce this section by catching just the top-level Exception
      catch (ConnectionException ex)
      {
            // a connection exception

            Console.Write(ex.ToString());
      }
      catch (SchemaException ex)
      {
            // a schema-read exception

            Console.Write(ex.ToString());
      }
      catch (SchemaCompareException ex)
      {
            // a schema compare exception

            Console.Write(ex.ToString());
      }
      catch (ScriptExecutionException ex)
      {
            // a script execution exception

            Console.Write(ex.ToString());
            Console.WriteLine("Script fragments that failed:");
            foreach (string err in ex.Errors)
                  Console.WriteLine(err);
      }
      catch (Exception ex)
      {
            // a generic exception

            Console.WriteLine("An unexpected error occurred.");
            Console.Write(ex.Message);
      }


You are done - your app can now compare and synchronize the schemas of two databases and it took you 5 minutes! And here it is, all of it in one place to make it easier for you to copy and paste:

using xSQL.Schema.Core;
using xSQL.Schema.SqlServer;
using xSQL.SchemaCompare.SqlServer;

namespace xSQL.Sdk.SchemaCompare.Examples
{
    class Examples
    {

        /// <summary>

        /// This example demonstrates a typical database comparison scenario.
        /// </summary>
        public static void SimpleCompare()
        {
            SqlServer xServer, yServer;
            SqlDatabase xDatabase, yDatabase;
            SqlSchemaCompare comparer;
            ScriptManager sqlScript;
            ScriptExecutionStatusEnum status;
            try
            {
                // create the left SQL Server object using Windows authentication

                xServer = new SqlServer(@"(local)");

                // create the right SQL Server using SQL Server authentication

                yServer = new SqlServer(@"(local)", "<user>", "<password>");

                // create the left database

                xDatabase = xServer.GetDatabase("Source");

                // create the right database

                yDatabase = yServer.GetDatabase("Target");

                // create the schema comparer

                comparer = new SqlSchemaCompare(xDatabase, yDatabase);

                // exclude some database objects

                comparer.Options.CompareUsers = false;
                comparer.Options.CompareSchemas = false;
                comparer.Options.CompareDatabaseRoles = false;
                comparer.Options.CompareApplicationRoles = false;

                // attach event handlers to these events in order to get some progress information during the schema read and compare

                comparer.LeftDatabase.SchemaOperation += new EventHandler<SchemaOperationEventArgs>(database_SchemaOperation);
                comparer.RightDatabase.SchemaOperation += new EventHandler<SchemaOperationEventArgs>(database_SchemaOperation);
                comparer.SchemaOperation += new EventHandler<SchemaOperationEventArgs>(database_SchemaOperation);

                // step 1: read the schema

                comparer.ReadSchema();

                // step 2: pair the database objects

                comparer.PairObjects();

                // step 3: compare the database schema

                comparer.Compare();

                // check for errors that could have occurred during the schema compare.

                // some errors are handled quietly and do not stop the process; those that are critical throw exceptions
                // quiet errors are collected and stored into the ErrorRepository object
                if (ErrorRepository.Instance.HasErrors())
                {
                    Console.WriteLine("Some errors occurred during the database compare");
                    Console.Write(ErrorRepository.Instance.GetErrors());
                }

                // check the database status; exit if no schema differences are found.

                if (comparer.SqlDatabasePair.ComparisonStatus == ComparisonStatusEnum.Equal)
                    return;

                // step 4: get the T-SQL script intended for the right database; that is the script that should be executed

                // on Target database to make it the same as the Source database
                sqlScript = comparer.GetRightDatabaseScript();
                if (!sqlScript.IsEmpty())
                {
                    // print the synchronization log

                    Console.Write(sqlScript.GetLog());

                    // print the synchronization script

                    Console.Write(sqlScript.GetScript());

                    // attach event handlers to ScriptManager object to get some progress info during the script execution                     sqlScript.SchemaScriptExecuting += new EventHandler<SchemaScriptEventArgs>(sqlScript_SchemaScriptExecuting);

                    // execute the sync script

                    status = sqlScript.Execute();

                    // check the execution and print any errors

                    if (status == ScriptExecutionStatusEnum.Succeeded)
                    {
                        Console.WriteLine("Database synchronization finished successfully");
                    }
                    else if (status == ScriptExecutionStatusEnum.Canceled)
                    {
                        Console.WriteLine("Database synchronization was canceled");
                    }
                    else
                    {
                        // check for quiet errors

                        if (ErrorRepository.Instance.HasErrors())
                        {
                            Console.WriteLine("Some errors occurred during the script execution");
                            Console.Write(ErrorRepository.Instance.GetErrors());
                        }
                    }
                }
            }
            catch (ConnectionException ex)
            {
                // a connection exception

                Console.Write(ex.ToString());
            }
            catch (SchemaException ex)
            {
                // a schema-read exception

                Console.Write(ex.ToString());
            }
            catch (SchemaCompareException ex)
            {
                // a schema compare exception

                Console.Write(ex.ToString());
            }
            catch (ScriptExecutionException ex)
            {
                // a script execution exception

                Console.Write(ex.ToString());
                Console.WriteLine("Script fragments that failed:");
                foreach (string err in ex.Errors)
                    Console.WriteLine(err);
            }
            catch (Exception ex)
            {
                // a generic exception

                Console.WriteLine("An unexpected error occurred.");
                Console.Write(ex.Message);
            }

        }
        private static void database_SchemaOperation(object sender, SchemaOperationEventArgs e)
        {
            //--exclude verbose messages

            if (e.Message.MessageType != OperationMessageTypeEnum.Verbose)
                Console.WriteLine(e.Message.Text);
        }

        private static void sqlScript_SchemaScriptExecuting(object sender, SchemaScriptEventArgs e)
        {
            Console.WriteLine("{0} {1}", DateTime.Now.ToString("HH:mm:ss"), e.Script);
        }
    }
}

//


You can download xSQL Schema Compare SDK from: http://www.xsql.com/download/sdk/sql_server_schema_compare/

Thursday, January 16, 2014

New xSQL Documenter with full support for SQL Server 2012 released

We have just released a new version of  xSQL Documenter:
  • Full support for SQL Server 2012, Analysis Server 2012, Report Server 2012 and Integration Server 2012
  • Improved diagrams with GraphWiz
  • Dropped support for SVG diagrams
  • Ability to exclude synonyms and sequences in Oracle
  • Bug fixes
If you have an active maintenance agreement you do not need to contact us, you will receive a new license for this version of the xSQL Documenter in the next two days.
 
You can download the new version from: http://www.xsql.com/download/database_documenter/  Notice that there are 3 different packages for download depending on which set of the SQL Server Client tools you might have installed on your machine. Also, each package contains 2 builds, a 64 bit version and a 32 bit version.
 

Wednesday, December 11, 2013

xSQL Schema Compare SDK 4 released

We just released xSQL Schema Compare SDK 4 with full support for SQL Server 2012 - implementing database schema comparison and synchronization functionality in your .NET application has never been easier. Built from the ground up with you (the developer) in mind the new SDK exposes a very intuitive object model that allows you to write your first schema comparison and synchronization app in minutes.

The new version of the SDK significantly improves the performance, robustness and scalability while giving you a lot more control over the process through numerous options that you can tweak, events that you can subscribe to and extensive logging.

xSQL Schema Compare SDK 4 supports SQL Server 2012, SQL Server 2008 and SQL Server 2005

Download the xSQL Schema Compare SDK 4 now and check it out.

Wednesday, December 4, 2013

2013 holiday specials are on

The rolling product slides on the main page of our site have been replaced by the "holiday" slide that invites you to unveil that special holiday present that we have in store for you. Don't hesitate, go ahead and "open the box" to see what today's special is, you will be pleasantly surprised. 

If you like what you see, don't delay to take advantage of it – if you delay you might have to wait a whole other year before that same deal is offered again. 

Season's Greetings and Happy Holidays!

Monday, September 16, 2013

SQL Data Compare Free - last chance

Last week when we ran the SQL Server Data Compare free promotion for a day we had quite a few complaints from users, especially from our European users, who got the email notification too late in the day and were not able to take advantage of this awesome deal. Therefore, we have decided to give everybody one more chance, and this time we are letting you know ahead of time. Here are the details:
- the window of opportunity opens on September 17, at 00:01:00 (UTC-05:00) and closes on September 17, at 23:59:00 (UTC-05:00)  - please do the time zone calculations before you contact us complaining that the code is not working.
- one license per user only - if you get more than one all your licenses will be invalidated and you will get into our naughty list.
- again, you will need to find the discount code which this time is composed of the first letter of the LAST feature (under the "Features" section on the product page) of the following products in order: xSQL Schema Compare, xSQL Data Compare, xSQL Script Executor, xSQL Profiler, xSQL Documenter, xSQL Builder, xSQL RSS Reporter, xSQL Object Search - so the code will have 8 letters. Once you find the code then do the following:
  • go to the SQL Server Data Compare page
  • click on "Order" button on the right hand side
  • under the "Licensing Options" select the first item "DPN2-1U"
  • on the next page, by default we include the 1 year maintenance which is not part of this deal so if you don't want to pay anything select the "No maintenance" option. Consider this step carefully as there is a new release with support for SQL Server 2014 coming in a few months.  
  • click on the "Add to Cart" button
  • on the shopping cart page plug in the discount code that you identified above and click on "Apply Discount" - that will subtract the full $349 from the price
  • proceed with the checkout to obtain your license.
You can start here: http://www.xsql.com/

Friday, August 30, 2013

How to create a stored procedure on multiple databases

I noticed this particular question asked on one of the SQL forums the other day, however, this same question can apply to any database objects, like how to create a function on multiple databases, how to create a view on multiple databases, how to create a table on multiple databases, etc. If you think about it just for a bit you will realize that in fact the generic question that covers all those particular cases and more is: how to execute a t-sql script against multiple databases.
Well the best, safest and most efficient way for executing or deploying t-sql scripts on multiple databases is to utilize xSQL Software's Script Executor tool. Here is the breakdown of the time you would need to spend to accomplish your task:
  • Download and install Script Executor -> 2 minutes max
  • Create a database group and add your servers and databases into the group -> 30 seconds per server
  • Create one or more script containers and add your t-sql scripts to those containers -> less than 2 minutes depending on where the scripts are and how you might need to organize them
  • Map scripts to databases and set execution priorities -> 2 to 3 minutes depending on how complicated your deployment scenario is.
  • (optional) Create a deployment package -> 10 seconds (you would create a deployment package if you wish to executed the scripts from a machine where you might not have the Script Executor tool installed)
  • (optional) Create a batch file that executes the deployment package created above OR that executes a saved deployment project from the command line -> 2 minutes
  • (optional) Create a scheduled task that executes the batch file -> 1 minute
So, in about 10 minutes you will have created an automated job that deploys the scripts you want to the servers and databases you want, when you want! Now whenever you might wish to deploy one or more scripts that you have created to those databases all you need to do is drop the scripts to the folder(s) to which the Script Containers created above are pointing to and you are done - your scheduled task will take care of the rest.
 
Download Script Executor now and see what you have been missing.

Wednesday, August 14, 2013

How to get list of tables, number of rows, data and index space

Here is a simple query that returns the complete list of user tables on a SQL Server database - it includes the schema name, table name, the date on which the table was created, the number of rows, the disk space occupied by the data in KB and the disk space occupied by the indexes:

SELECT sschemas.name AS SchemaName
               ,sobjects.name AS TableName
               ,sobjects.create_date AS CreatedOn
               ,sobjects.modify_date AS ModifiedOn
               ,MAX(sstats.row_count) AS NoRows
               ,SUM(CASE
                               WHEN (sstats.index_id < 2)
                                       THEN sstats.in_row_data_page_count + sstats.lob_used_page_count +
                                                   sstats.row_overflow_used_page_count
                                        ELSE 0
                            END) * 8 AS DataSpaceKB
                 ,SUM(CASE
                                 WHEN (sstats.index_id >= 2) THEN sstats.used_page_count
                                 ELSE sstats.in_row_used_page_count - sstats.in_row_data_page_count
                   END) * 8 AS IndexSpaceKB
FROM sys.schemas AS sschemas
            INNER JOIN sys.objects AS sobjects ON sschemas.schema_id = sobjects.schema_id
            INNER JOIN sys.dm_db_partition_stats AS sstats ON sobjects.object_id = sstats.object_id
WHERE sobjects.type = 'U'
GROUP BY sschemas.name, sobjects.name, sobjects.create_date, sobjects.modify_date
ORDER BY sobjects.name

A couple of things you need to know in order to understand this:
  • one page is equal to 8K in size 
  • index_id values are 0 for the heap, 1 for the clustered index and > 1 for nonclustered indexes
  • in_row_data_page_count represents the number of pages used for storing in-row data and it only includes the leaf pages
  • lob_used_page_count represents the number of pages used for storing out of row text, n/varchar(max), n/varbinary(max), image, and xml columns.
  • row_overflow_used_page_count represents the number of pages for storing row overflow
  • in_row_used_page_count represents the total number of pages in use to store in-row data including both leaf and non-leaf pages. Hence, to determine the index space for the clustered index we subtract the in_row_data_page_count from the in_row_used_page_count to get only the non-leaf pages which should be attributed to the index space.
Any questions or comments please leave them here.

If you have not tried our SQL Server comparison download them now http://www.xsql.com/download/sql_server_comparison_bundle/ - quick and easy to install, even easier to use, fast, robust and completely free for SQL Server Express.

Tuesday, August 13, 2013

SQL Schema Compare and xSQL Builder new builds available

New builds of SQL Server Schema Compare and xSQL Builder are available for download.
The following fixes are included in both tools: 
  • an issue related to conversion of varchar(max) data type to image data type;
  • error triggered by foreign keys with the same name created on different tables;
  • issue related to dependencies between a full-text index and the unique key/index associated with it;
  • small corrections related to the conversion of char, varchar data types to float and real data types;
  • issue related to parsing of SQL Server multi-line comments in the object definition;
  • issue with the serialization of user-defined data type binding to rules and stand-alone defaults.
Has our SQL Schema Compare (xSQL Object) saved you time? If yes, please consider recommending it on LinkedIn.

Thursday, August 1, 2013

t-sql list of currencies of the World

On February 15, 2022 we released easy lookups by xSQL Software https://lookups.xsql.com/ - you can now get the currencies list and other commonly used lists for free. You can consume those lists directly as JSON/xml services in your JavaScript apps, or download in one of the following, ready to use formats:
  • JSON
  • XML
  • CSV
  • SQL Server insert statements
  • Oracle insert statements
>>> original article below - links replaced with the new lookup link

The following script (https://lookups.xsql.com/ ) creates a "currencies" table and populates it with the complete ISO 4217 list of international currency codes (edition ISO 4217:2008).
Note that the first two letters of the [AlphabeticCode] in the Currencies table correspond to the [ISO_ALPHA2] code on the Countries table which you can get from https://lookups.xsql.com/, whereas the [NumericCode] in the Currencies table is in most cases the same as the [NumericalCode] in the Countries table.
Please note that the list is current as of the date of this post.

If you have any questions or comments please post them here.