10

How do I update a BLOB field only using TSQL (for example from SSMS and not using any code such as ADO.Net or Linq)?

yoel halb
  • 12,188
  • 3
  • 57
  • 52

1 Answers1

20

There are two ways to SELECT a BLOB with TSQL:

SELECT * FROM OPENROWSET (BULK 'C:\Test\Test1.pdf', SINGLE_BLOB) a

As well as:

SELECT BulkColumn FROM OPENROWSET (BULK 'C:\Test\Test1.pdf', SINGLE_BLOB) a

Note the correlation name after the FROM clause, which is mandatory.

The second version can be used for a UPDATE as in the following example:

UPDATE MyTable 
SET blobField = 
   (SELECT BulkColumn FROM OPENROWSET (BULK 'C:\Test\Test1.pdf', SINGLE_BLOB) a) 
WHERE (CriteriaField = @criteria)

For partial updates one can use the SET .WRITE mutator as described in this MSDN article, here is the syntax:

UPDATE MyTable SET BlobField .WRITE (expression, @offset, @length) WHERE (CriteriaField = @criteria)

Note that the WRITE mutator can only be used on NON-NULL fields.

In fact this can also be used to do a full update (if the column does not contain NULL), by setting @offset to 0 and @length to NULL (or to the actual length), as in the following example:

DECLARE @tmp VARBINARY(MAX) --Change to the correct datatype here
SELECT @tmp = BulkColumn FROM OPENROWSET (BULK 'C:\Test\Test1.pdf', SINGLE_BLOB) a
UPDATE MyTable SET BlobField .WRITE (@tmp, 0, NULL) WHERE (CriteriaField = @criteria)
yoel halb
  • 12,188
  • 3
  • 57
  • 52
  • In fact the first version of the SELECT is really nothing more then the second SELECT just using instead SELECT *, Still I included it as a separate version since this is what the MSDN and other online resources use in examples and it appears that many developers think of it as the only way of doing it – yoel halb Aug 06 '12 at 03:29
  • The selects give me errors like 'Cannot bulk load. The file X does not exist' and 'Cannot bulk load because the file X could not be opened. Operating system error code 3(The system cannot find the path specified.).' But the file is clearly out there in the right place and the path is correct. Am I missing some setting? On SQL Server 2012. The SQL Server user has full control on the C drive and the file in on the C drive. – alexherm Jun 13 '19 at 16:20