Generate Data Insert Scripts Using Hex Strings to Preserve Data
SQL Server 2000: Not Supported**
SQL Server 2005: Tested
SQL Server 2008: Tested
SQL Server 2008R2: Tested
SQL Server 2012: Not Tested
Date: 28 Nov 2011
There are several well publicised methods of generating data insert scripts for SQL Server tables and with good reason - until SQL 2008, this feature was not available through any of the Microsoft SQL Server management toolset. SQL 2008 does provide this function, as does SQL 2008 R2 (although Microsoft decided to move its location giving the initial impression that it had disappeared)
However, these methods all script text using the standard unicode text string i.e. N'This is text'.
There will always be some user (or 3rd party software vendor) who will ruin your day by including control characters or other non-text characters in the text data. Fun, fun, fun.
This script adopts a new approach by converting all characters in a text column into one Hex string.
These will be processed by a standard insert statement - you just have to look as some of the SQL Server Replication stored procedures to find examples of this (one of the common SQL Injection attacks is even delivered using strings in this format in attempt to mask the malicious intent of the string)
The code is not particularly performant for larger data volumes, but then this kind of task is normally required when setting up or transferring lookup table data between servers/databases. For larger data volumes, I would recommend using BCP in native format mode.
**NOTE: This code could be adapted for SQL 2000 by replacing the VARCHAR(MAX) variables with VARCHAR(8000), but the verbose nature of a hex string (just over 4 * the size) will limit the size of the text strings that can be processed