Wednesday, April 29, 2009

Old SQL Server 2005 merge replication bug, how to determine version on the subscribers and details

I got the following email from, unfortunately when I replied to this colleague, the email bounced. I'm hoping he can Google this up.

Hi Lizet,

I just read your article on about data loss in Merge Replication. Unfortunately we are experiencing this exact same bug. I have already upgraded the subscriber server to SP3. Do you know if the fix for this issue is included in SQL Server Express SP3 and will it get applied if I just upgrade an existing instance from SP2 to SP3? Or do I need to do a complete uninstall and reinstall? Also, is there anything I can do to verify the subscriber instance had the correct patches applied to it? I appreciate your help on this and the article you wrote. We have a lot of work ahead of us restoring data lost but it could have been worse if not for this article.

I appreciate your time.

My replies:

As far as I can remember any SQL Server Engine (whether Express or Standard or Enterprise) had the problem.
The publisher and the distributor (which can only be a Standard or an Express instance) should be patched as well. Any engine with a version lower than 9.00.3228.00 should be patched, whether applying SP3 or only the Cumulative Update they launched after the replication problem came to the public light.
You can check the version at the subscribers using sqlcmd.
If your subscriber engines are installed as the default engine and use windows authentication, you can connect to them using the following command, you need to be an administrator on the machine in order to apply the CU:
sqlcmd -E
checking the version on the sqlcmd command prompt would be:
> select @@version
I remember patching the subscribers was a pain, as we didn't want to push the update automatically and we connected to every single subscriber remotely to make sure the patch (CU6 for SP2 in our case) was applied properly.

I added a post to my blog with the line of code that caused the mess. The link is
Hope this helps, good luck


I forgot to answer two of your questions:
Do you know if the fix for this issue is included in SQL Server Express SP3
Yes, the fix is included in SP3. Make sure you patch the publisher and distributor as well, not only the subscribers.
and will it get applied if I just upgrade an existing instance from SP2 to SP3?
Or do I need to do a complete uninstall and reinstall?
No, just patch.

Usually you can recover the published database from a previous backup but as you usually don't keep synchronized backups of each subscriber, you have to recreate the publication and subscriptions, potentially destroying any data at the subscribers that has not been merged yet. Or you could copy the subscriber database to a different location, recreate publication and subscription and manually add the data that didn't merge from your saved database to the newly merged database.

Hopefully this reaches you, again good luck recovering the data.

Labels: ,

Thursday, October 09, 2008

If you delete a data partition on a merge repl, make sure you do this additional clean up

We wanted to delete old data partition on our merge publication. The Management Studio has a nice UI to view the data partitions and generate the dynamic snapshot per partition, also to delete the partitions you no longer need.

Be warned that this nice UI delete button won't delete the partition folder at the distributor nor will delete the dynamic snapshot job at the distributor. If you try to add a partition with the same filter token, it will fail.

In order to have a fresh start for that partition value you should:

1. Verify that the subscriptions that use that data partition don't exist anymore.
2. Delete the data partition using the Publication Properties UI
3. Delete the data partition using the sp_dropmergepartition stored procedure:

use [Published_Database]
exec sp_dropmergepartition @publication = N'Publication_Name', @suser_sname = N'', @host_name = N'the string we use to filter the data part'

4. Delete the replication partition folder manually at \\distributor\repldata

Happy data merging!

PS SQL Server version 9.00.3228

Labels: , ,

Wednesday, September 10, 2008

More on merge replication with subscription expiring after a period of time

We have a merge replication topology with pull subscriptions. We have a setting to expire the subscriptions that haven't synchronized in the past X days. This setting was mainly due to optimizations, when you don't expire your subscriptions the amount of metadata to be used grows and grows and your merge process suffers.

The drawback on this setting is that it also makes the snapshot obsolete after X days for any new or reinitialized subscription.

When you add a new subscription to your publication and the snapshot was generated X-1 days ago you will have the following error:

The snapshot for this publication has become obsolete. The snapshot agent needs to be run again before the subscription can be synchronized.

At first we wondered why we got this error when the rest of the subscriptions were working just fine and also wondered what impact would have on the existing subscriptions to regenerate the snapshot.

The answer is: no impact.

We got the explanation from one of Hilary Cotter's replies:

The snapshot contains all the data, schema and metadata required to create
all the objects on the subscriber. After one day in your case the metadata
on the publisher is purged and what is in the snapshot will not be
sufficient to sync with the publisher, hence you need a new snapshot.

You want to set a small number so that not a lot of data goes across the
wire, but a big enough number so that the majority of your subscribers will
sync within the expiration time. If you set it to an infinite amount - never
expires, a lot of data will have to go to the subscriber to get it back in

And another reply with further clarifications:

The answer lies in the MSmerge_contents and MSmerge_genhistory tables.
These two tables hold the list of data changes that happened for the
past x days, x being the subscription expiration days. After x days the
record of the data change expire from the MSmerge_contents table. The
implication of that is that existing subscriptions that have not
synchronised for the past x days will then not be able to merge that
change anymore. The same holds true for creating new subscriptions with
an old snapshot - remember the snapshot also contains data. If the
snapshot was created x-2 days ago you will missing two days of data
changes that has already expired from the MSmerge_contents table.


a thread on MSDN:

Labels: ,

Wednesday, August 06, 2008

This merge replication error: The merge process could not connect to the Publisher 'Server:database' is so misleading

We have a merge topology in place with pull subscriptions, this is the merge agent runs at the subscribers.
One of our subscriptions in had the error that the merge process couldn't find the server. The server was there and the ping was fine, also the Replication Monitor was able to register the error with the x mark.

The details of the ertor are as follows:

Command attempted:

{call sp_MSensure_single_instance (N'Merge Agent Name', 4)}

Error messages:

The merge process could not connect to the Publisher 'Server:database'. Check to ensure that the server is running. (Source: MSSQL_REPL, Error number: MSSQL_REPL-2147199368)
Get help: http://help/MSSQL_REPL-2147199368

Another merge agent for the subscription(s) is running or the server is working on a previous request by the same agent. (Source: MSSQLServer, Error number: 21036)
Get help: http://help/21036

Our error was due to the second cause. It seems the subscriber had lost power while replicating, and any replication after that could not acquire a lock for the merge agent. We restarted the subscriber machine, reinitialized the subscription, with no luck. Only when we dropped the subscription and recreated it again the subscriber was able to run the replication agent again. Just a curious note for the future as this error is not well documented. The only MSDN forum thread that deals with is is still unanswered here...

Labels: ,

Thursday, July 31, 2008

My wish list for SSRS 2005 and 2008

Right now I'm swamped making reports in SSRS 2005. Even though that might be considered a junior's task I found it interesting. Last time I created report templates was 10 years ago with Quick Reports and VB 6 in the late 1990s :-p

My team recommended SSRS over Crystal Reports and VTO mainly because we have had a previous bad experience with word templates for report generation and really liked the idea or having the report engine accessible using a web service. Also being the RDL files xml with a documented schema, instead of the proprietary Crystal Report format, made us believe SSRS might go farther in the long run. Price was also a consideration for ruling out Crystal Reports. One of the big points towards this decision was the Report Manager in SSRS. Deploying our reports independently of the application where they will be viewed allow us to deploy and test the reports in parallel. There is no need to wait until the main application goes to QA. Report subscriptions was another plus.

The purpose of this short post is not to compare those three technologies though. You can see a good comparison of Crystal Reports vs SSRS here.

Our initial hesitation of putting most of our eggs on the SSRS's basket is almost gone now, but not without having a wish list that would make the maintenance of our solution easier:

- Widows and Orphans control, there's a hack if you use a rectangle control to group elements, KeepTogether property for a table doesn't work
- Full aligned text, no workaround for this AFAIK.
- Reuse datasets in the reports that belong to the same project.
- Reuse images
- Reuse custom code and make it visible other than in the Report Properties->Code Tab
- Be able to re-use headers and footers on all the reports on the project.
- Be able to use more than one reportitem in an expression for an element in the header or footer.
You have to do lots of hacks in order to achieve this.I have an example of doing this using a dataset and an internal report parameter after I gave up on using the ReportItems for hiding or showing header elements.
-Barcode print in PDF, some barcode fonts get distorted when the report is rendered as a PDF,
so you have to rely on third party components such as Aspose.Barcode. Microsoft SSRS team fixed some fonts on the SP2 for SQL Server 2005 but unfortunately the font we use is not fixed yet.
-More alignment with the Visual Studio project layout. Being able to group reports in subfolders, being able to see the shared datasets in a project folder, the custom code in a project folder, being able to see the referenced external assemblies similar to the references added to the visual studio web and windows projects.
I know that aligning the web rendering with the PDF rendering might be too much to ask, but it would be really nice if the report rendered in HTML form would look similar to its PDF counterpart. Right now you cannot rely on the HTML view at all
when your final renderer is PDF.
- Rendering RTF text out of the database (I still have to explore this on 2008)
- Using CSS to apply styles to your textboxes.

Hope this helps if you have to make a technology decision, I'm sure I'll increase the wish list soon...

Labels: ,

Tuesday, July 08, 2008

Lets rectify this error (was Compressed snapshot check makes it fail on one subscriber)

I published a post with the wrong title. It was Compressed snapshot check makes it fail on one subscriber

However the file dynsnapvalidation.tok appears inside the partitioned snapshot whether you select snapshot compression or not. This .tok file shows up if you create data partitions per parameterized filter.

Labels: ,

Wednesday, April 09, 2008

Tips and tricks for applying SQL Server 2005 hotfixes

Tips and tricks:
  • You can install any hotfix in silent mode passing the parameter /quiet to the executable in the command prompt or in a batch file. This is extremely helpful if you want to push the hotfix installation with a third party tool and without the wizard interface
  • The /? parameter will give you the rest of the options for installing the hotfix. A very useful option is /allinstances
  • You might wonder why would you like to run any hotfix unsupervised, it might not make sense on a stand alone server but it makes sense when you have a few dozen of remote subscribers and/or you deploy SQLE as part of a SmartClient application. Your batch script can provide you with the installation log afterwards.
  • You cannot rollback a hotfix or a SQL Server Service Pack. The only option is to reinstall the SQL Server instance. Plan your testing very carefully...
  • If you have a virtual drive on the box where you're applying the hotfix beware that it will try to unzip its files in it. If that virtual drive is read only or used for another purposes you might have troubles. To determine if there is a virtual drive on your box run the command subst. You can always delete the virtual drive apply the hotfix (it will unzip on c: or the drive where the windows installation is, as expected) and put back the virtual drive after the hotfix is applied.

Hope this helps and happy patching!


Wednesday, February 20, 2008

The fix for batch deletions at Publisher when use_partition_groups is set to false In Merge Replication is indeed there!!!


The fix is in there. Please see previous post for the original bug description. We had problems when not using partition groups on our merge replication topology, whenever there were batch deletions caused by filtering those rows were deleted at the publisher during the next replication.

The faulty stored procedure was sp_MSdelsubrowsbatch

The faulty line of code, believe it or not, a single line
on the faulty sproc:

-- change tombstone type for the non-original rows (the rows that got deleted via expansion).
update dbo.MSmerge_tombstone
set type = 1
(select distinct tablenick, rowguid from
#notbelong where original_row <> 1) nb,
dbo.MSmerge_tombstone ts
where ts.tablenick = nb.tablenick and
ts.rowguid = nb.rowguid

On the sproc after CU6:
update dbo.MSmerge_tombstone
set type = @METADATA_TYPE_PartialDelete
(select distinct tablenick, rowguid from
#notbelong where original_row <> 1) nb,
dbo.MSmerge_tombstone ts
where ts.tablenick = nb.tablenick and
ts.rowguid = nb.rowguid

Basically the deletions caused by filtering (Partial deletes) were marked as tombstone or user deletions.

Given the following variable declarations:

declare @METADATA_TYPE_Tombstone tinyint
declare @METADATA_TYPE_PartialDelete tinyint
declare @METADATA_TYPE_SystemDelete tinyint

and assignation:

set @METADATA_TYPE_Tombstone= 1
set @METADATA_TYPE_PartialDelete= 5
set @METADATA_TYPE_SystemDelete= 6

If you ever doubted the power of a single line of code... :-p

Happy coding guys!

Labels: ,

Cumulative Update Number 6 for SQL Server 2005 SP2 is out!!!

Hi DBAs and Database Developers out there,
Finally the long awaited CU#6 was released on Feb 18th near mid night.

946608 Cumulative update package 6 for SQL Server 2005 Service Pack 2;EN-US;946608

I'm currently testing our merge replication issues with this CU.

Even though the bug described in the DevX article is not in the KB article list, we got confirmation that the fix is on the CU#6.

So far the identity automatic management problem described on my previous post remains the same. If the user making the inserts is not a db_owner, automatic identity management ain't going to happen on your publisher...

Labels: ,

Thursday, February 14, 2008

Identity Range not working for Merge Replication in SQL Server 2005

Back in Sept 2007 I blogged about the problem we were having with the identity range in merge replication:@@identity not working after SQL Server 2005 upgrade The problem continued until today, this post is to explain what we figured out.

The error message that describes this problem reads as follows:

[548] The insert failed. It conflicted with an identity range check constraint in database 'DatabaseName', replicated table 'dbo.TableName', column 'ColumnNameId'. If the identity column is automatically managed by replication, update the range as follows: for the Publisher, execute sp_adjustpublisheridentityrange; for the Subscriber, run the Distribution Agent or the Merge Agent.

The identity range adjustment happens after every insert in the given article. The code responsible for the identity check adjustment is on the system trigger for the published article:
MSmerge_isn_GUID where GUID is the GUID for the given article.
if is_member('db_owner') = 1
-- select the range values from the MSmerge_identity_range table
-- this can be hardcoded if performance is a problem
declare @range_begin numeric(38,0)
declare @range_end numeric(38,0)
declare @next_range_begin numeric(38,0)
declare @next_range_end numeric(38,0)

select @range_begin = range_begin,
@range_end = range_end,
@next_range_begin = next_range_begin,
@next_range_end = next_range_end
from dbo.MSmerge_identity_range where artid='BAEF9398-B1B1-4A68-90A4-602E3383F74A' and subid='0F9826DB-50FB-4F73-844D-AE3A111B4E1C' and is_pub_range=0

if @range_begin is not null and @range_end is not NULL and @next_range_begin is not null and @next_range_end is not NULL
if IDENT_CURRENT('[dbo].[TableName]') = @range_end
DBCC CHECKIDENT ('[dbo].[TableName]', RESEED, @next_range_begin) with no_infomsgs
else if IDENT_CURRENT('[dbo].[TableName]') >= @next_range_end
exec sys.sp_MSrefresh_publisher_idrange '[dbo].[TableName]', '0F9826DB-50FB-4F73-844D-AE3A111B4E1C', 'BAEF9398-B1B1-4A68-90A4-602E3383F74A', 2, 1
if @@error<>0 or @retcode<>0


As you might have noticed already, if the insertion is made by a user that is not member of the db_owner database role, the identity adjustment won't happen. I believe this is a bug, not a feature. It forces the users that are allowed to do insertions to be owners of the database, or they will have the run out of identities error quite often and a manual adjustment will be required.

What the savvy DBA can do:

The template for all of the MSmerge_ins_GUID triggers are on the model database, these triggers are created by the system stored procedure: sp_MSaddmergetriggers_internal

If you change the code on this system stored procedure any new database creation will have the proper template for creating the merge insertion triggers. For the existing databases, you might like to modify the MSmerge_ins_GUID trigger manually, for now.

At the time I'm writing this post I'm not aware if this issue is addressed on any cumulative update. There is a similar case on the Cumulative Update released on January 15, 2008

Happy coding guys!

Labels: ,

Thursday, January 17, 2008

Merge replication issues in SQL Server 2005 and comments on MS employee's blog

Hi all,
As I mentioned in my previous post, i would provide details of the data loss scenarios in Merge Replication topologies with SQL Server 2005. The details were published in this addendum to the original DevX article:

UPDATED SQL Server 2005 Bug Alert: Data Loss in Merge Replication

the article is basically two repros to illustrate the data loss when the partition groups are not use in the publication. The workaround is not published and the definite solution should be available on SQL SErver 2005 SP3 or the upcoming cumulative update in February 2008.

Today I came across a blog post regarding SQL Server bugs and how to provide the information to tech support or to the Connects program.

Please read this blog post if you are posting/investigating bugs. The more information you provide, the faster the bug might be scheduled for a fix:

Getting Your "Favorite" SQL Server Bug Fixed

What is interesting on that blog post is one of the comments from a MS employee "anna":

I'm sometimes amazed how personal people takes the bug issue. If you look at users you can sometimes think that the users think we have a complete bug list or that we have super powers to figure out what the problem are. And believing that a rotten attitude gets the problem fixed faster is so stupid.

But if you look at it from the other perspective, I often find developers taking pride in classifying something as a bug. In these days of agile and customer driven development, why taking so much pride into saying if something is a bug or a change request.

During the past two years we've gotten two synchronization bugs fixed in SQL Server 2005. My tips: be honest, give all information you have, understand that everyone wants to fix the bugs and don't forget that the guys fixing and confirming the stuff are people. Often really nice people. And also remember that reporting a bug is like going to the ER: sometimes there are people who are sicker than you and they need help first.

I know there is no excuse to use fault language or be rude to have your bug scheduled first, however, there is also no excuse to have data loss due to insufficient testing or a newly introduced bug.
I can only speak for myself, but in our case the merge topology had worked fault free for over a year before we upgraded to the 2005 version.
We are humans and we err, but we are also accountable for our code and our testing procedures. It's not a matter of taking pride on pointing out a fault. I would rather not have had the data loss issue at all and the overtime and stress that happened after in order to recover the data and avoid future losses.

Why taking so much pride in the work we do or the code we write? Maybe it's better to ask why not?


Wednesday, December 19, 2007

Merge Replication parameterized row filtering, beware of the optimizations

I haven't blogged in a while, mostly due to my workload that has sky rocketed.
My most recent challenge is with SQL Server 2005 Merge Replication.

We have had quite a few undesirable effects when we upgraded our subscribers from ole good MSDE to SQL Server Express.
The side effects led to data loss and emergency fixes, in a really chaotic way. This data loss didn't happen with MSDE.

The article I recently published on DevX described a data loss scenario with SQL Server 2005 Ent as publisher/distributor and MSDE or SQLE as subscriber.

The scenario we got recently happens only with SQLE in the subscribers and is related to the parameterized filter optimizations in SQL Server 2005.

Tweaking the parameters @use_partition_groups and @keep_partition_changes produce different side effects that go from data loss to inability to merge the data, the parameterized filters stop working.

If you're interested on the subject hang on, I will publish repros in the next post.

If anyone knows how to set up the Windows Synchronization Manager for Verbose History Logging to output to a file, please comment here, all my attempts have failed.

Cheers and happy holidays!

Labels: ,

Saturday, November 03, 2007

SQL Server Merge Replication issues

After a month of talking over the phone with Microsoft tech support and more than a month and a half of struggling with then problem and trying to isolate the cause; I put together a short article on how to lose your data with merge replication if you use parameterized row filtering and upgrade your publisher from SQL Server 2000 to SQL Server 2005.
The details of the problem, steps to reproduce the behavior and scripts can be found on this article published on DevX:
SQL Server 2005 Bug Alert: Merge Replication Could Mean Data Loss

My main purpose is to speed up the resolution, so any comments, workarounds or similar cases you might find, please give me a shout.
Have a great weekend!


Labels: ,

Monday, October 01, 2007

More on "Breaking Changes in SQL Server 2005 Replication"

We finally launched our external sql server 2005 with merge replication with pull subscriptions. After extensive QA testing, surprising data loss due to filtering, more testing with new parameterized row filter, we finally made it.

Right after we launched the servers (our publisher and distributor) and the subscribers began to synchronize we had a few conflicts we hadn’t seen in any of the test environments.

The conflict cause was CONNECT REPLICATION permission missing on the users; the server data overwrote the client data on each case.

The Books Online documentation is pretty scarce on this new permission. It only says that if you have CONTROL permission at Database level, the CONNECT REPLICATION permission is implied on the database. Also if you have CONTROL SERVER permission at server level, the CONNECT REPLICATION permission is implied as well. Other than that, there isn’t much.

The official article documenting the breaking changes can be found here:

and it does not mention the difference in permissions.

The breaking change here is that this permission that you can set through the Securables item on the user properties is brand new to SQL Server 2005.

On a SQL Server 2000 engine, the Management Studio looks like:

While on SQL Server 2005 the set of permissions for a given database looks like:


Tuesday, September 04, 2007

@@identity not working after SQL Server 2005 upgrade

After our server upgrade to SQL Server 2005, some of the stored procedures stopped working. The reason, the change in behavior of the @@identity function in 2005:

The value of @@identity is not restricted by current scope and can be affected, for example, by triggers. I.e. if original 'insert' deals with table T1, and the table T1 has a trigger that inserts rows into table T2, then after the original insert is done the @@identity will show new value for the table T2 (not for the T1 as might be expected!!!)

The suggested solution is using SCOPE_IDENTITY()function instead of @@identity. This function IS restricted by the scope and for the example above it will return new identity value for the original table T1 (not for T2 or any other table affected by triggers).

It seems to me that SELECT MAX(T1) FROM T1 is not the best solution, because T1 (and any other) table can be updated simultaneously from multiple sessions and the maximal value is not always guaranteed.

If you have merge replication going on, be aware that now replication uses triggers that were not present in 2000:

For instance - insert trigger MSmerge_ins_5D17CE9EBD2142E3ADC630C47F017946 which does insert rows into other system table with identity column!!! We didn't see these triggers in SQL 2000 database which may explain why the @@identity worked fine in the same code under SQL 2000.

Hope this helps and happy upgrading!



Friday, August 10, 2007

SQL Server Express Command - line installation (just a link to the good stuff)

We developers are all a little bit lazy, time conscious, we don't like to perform the same installation/upgrade over and over on 30+ remote machines.
It is Friday, and even though I added this link to my bookmarks already, I know it will take me a few minutes to find on Monday... yes, my bookmarks are that messy.
I need to create a cmd install batch that will
  1. Upgrade the local MSDE instance to SQL Express 2005
  2. Use Advance features during the installation as I'm not creating a new instance but upgrading the default one.
  3. Add the replication components that will be needed for the merge replication
  4. Add the client components in case I need to connect remotely to that rebel local instance :-p
  5. Add the Connectivity components that will install the SMO and RMO (Server Management Objects and Replication Management Objects). I'm using both namespaces to trigger/manage replication from this .NET smartie client.
My cheat sheet is here:

Command-line installation

It doesn't seem too complicated, let's wait for Monday to see how it goes. Now I'm still working on my RMO code. We had Replication pretty much working with the a Replication ActiveX component for MSDE but this component is deprecated for 2005.

Have a nice weekend!


Thursday, August 02, 2007

Merge Replication and our need to upgrade hardware

We've all been pretty busy lately with a juicy project. We have a client application that runs on TabletPCs. Among other interesting parts of this project we have SQL Server Merge Replication going on. We used to have a topology of SQL Server Enterprise Edition for the Publisher and Distributor and the reliable MSDE for the subscribers.
A few months ago our excitement increased when the company decided to migrate some of the servers to SQL Server 2005 Ent.
The excitement continue but we're having quite a few headaches with the replication. Our main problem is the hardware. Our client boxes have merely 500MB of RAM and the recommended requirements for SQL Server 2005 Express edition is 512, oh joy.
We tried to keep MSDE alive and use it still as subscriber but we use some of the features that invalidate the compatibility, in particular the Parameterized Row Filtering. More details on the incompatibility on this MSDN Reference. Please see the topic Compatibility Level for Merge Publications where it specifies that parameterized row filtering requires Compatibility Level for Merge Publications 90RTM or higher.

The solution, it seems we upgrade our subscribers to SQL Server Express 2005 and hope they still work at a decent level with the scarce hardware, or upgrade and hope there is budget for a hardware upgrade too :-p, at the end it's all about budget, right?



Friday, March 16, 2007

SQL Server and binary fields (images)

No matter how much I disagree on putting image files into SQL Server, I had to handle this on a project.

We had to provide update statements to insert binary data into production servers from the data we had on the test servers. The statement had to be written in T-SQL, period.

Everything would have been a fairy tail if Query Analyzer wouldn't have the 8K result limit. Most of the images were bigger than 8K. This limitation does not apply to the data you use on the query you're running but on the buffer that stores the results to show in QA.

We ended up writing a small console app with ADO.NET to retrieve the binary data, but guess what, you cannot insert this data as it is with a T-SQL statement. We shortly after discovered we could have used a third party tool such as SQL Bundle from red-gate to do this. Did I say before that I just LOVE SQL Compare?
The binary data has to be converted to its hexadecimal equivalent so it can be used in an update or insert statement, you can not insert whatever you get from the database into your T-SQL queries.

Code samples follow:

The ADO.NET part (pretty basic):

this.sqlCommand1.CommandText="SELECT [Image field] FROM table where ID=something";

byte[] barrImg=(byte[])sqlCommand1.ExecuteScalar();

string strfn=Convert.ToString("yourfilename.txt");
FileStream fs=new FileStream(strfn,FileMode.CreateNew);

The hexadecimal conversion part, basic too:

char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7','8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
char[] chars = new char[barrImg.Length * 2];
for (int i = 0; i <>
int b = barrImg[i];
chars[i * 2] = hexDigits[b >> 4];
chars[i * 2 + 1] = hexDigits[b & 0xF];

string results;
results=new string(chars);

StreamWriter strWr = new StreamWriter("yourhexdatafile.txt");

Note: VB.NET has a Hex function for the hexadecimal conversion.