Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Manually inserting varbinary data into SQL Server

Tags:

sql

sql-server

We have a SQL Server table for user settings. Originally the settings were domain objects which had been serialized as XML into the table but we recently begun serializing them as binary.

However, as part of our deployment process we statically pre-populate the table with predefined settings for our users. Originally, this was as simple as copying the XML from a customized database and pasting it into an INSERT statement that was ran after the database was built. However, since we've moved to storing the settings as binary data we can't get this to work.

How can we extract binary data from a varbinary column in SQL Server and paste it into a static INSERT script? We only want to use SQL for this, we don't want to use any utilities.

Thanks in advance, Jeremy

like image 354
Jeremy Jarrell Avatar asked Jun 29 '09 14:06

Jeremy Jarrell


People also ask

What is VARBINARY data type in SQL Server?

varbinary [ ( n | max ) ]Variable-length binary data. n can be a value from 1 through 8,000. max indicates that the maximum storage size is 2^31-1 bytes. The storage size is the actual length of the data entered + 2 bytes. The data that is entered can be 0 bytes in length.

What is the difference between varchar and VARBINARY?

The VARBINARY type is similar to the VARCHAR type, but stores binary byte strings rather than non-binary character strings.

How can we insert a data into a view?

You can insert data through a single-table view if you have the Insert privilege on the view. To do this, the defining SELECT statement can select from only one table, and it cannot contain any of the following components: DISTINCT keyword. GROUP BY clause.


3 Answers

You may find it easier to store a template value in a config table somewhere, then read it into a variable and use that variable to fill your inserts:

DECLARE @v varbinary(1000)
SELECT @v = templatesettings from configtable

INSERT INTO usertable VALUES(name, @v, ....)
like image 176
Jeremy Smyth Avatar answered Oct 13 '22 01:10

Jeremy Smyth


From SQL Server 2008 onwards you can use Tasks > Generate Scripts and choose to include data. That gives you INSERT statements for all rows in a table which you can modify as needed.

Here's the steps for SQL 2008. Note that the "Script Data" option in SQL 2008 R2 is called "Types of data to script" instead of "Script Data".

like image 21
Rory Avatar answered Oct 13 '22 00:10

Rory


I presume you're OK with utilities like Query Analyzer/Mangement Studio?

You can just copy and paste the binary value returned by your select statement (make sure that you are returning sufficient data), and prefix it with "0x" in your script.

like image 35
David M Avatar answered Oct 13 '22 01:10

David M