17.07.2015 Views

The Art of SQL Server FILESTREAM - Red Gate Software

The Art of SQL Server FILESTREAM - Red Gate Software

The Art of SQL Server FILESTREAM - Red Gate Software

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 3: Accessing <strong>FILESTREAM</strong> Data from Client ApplicationsTo avoid additional round trips to the database, the stored procedure or T-<strong>SQL</strong> batchthat is used to perform the INSERT operation can also return the <strong>FILESTREAM</strong> transactioncontext <strong>of</strong> the current transaction and the logical path to the <strong>FILESTREAM</strong> datafile associated with the newly inserted record. <strong>The</strong> client application can then use thesevalues to access the <strong>FILESTREAM</strong> data.Since it is not possible to use the streaming API to create a new <strong>FILESTREAM</strong> data fileand associate it with a <strong>FILESTREAM</strong> column, to create a new record and save the BLOBdata into the <strong>FILESTREAM</strong> column the client application must use two steps.1. Execute a T-<strong>SQL</strong> statement to create a new record along with a dummy <strong>FILESTREAM</strong>value. Inserting a fake value such as 0x into the <strong>FILESTREAM</strong> column will force <strong>SQL</strong><strong>Server</strong> to create a <strong>FILESTREAM</strong> data file and associate it with the column.2. Once the <strong>FILESTREAM</strong> data file has been created, the client application can use thePathName() value <strong>of</strong> the <strong>FILESTREAM</strong> column in the newly inserted record to accessthe <strong>FILESTREAM</strong> data file and write the BLOB data into it.An alternative solution involves not allowing NULL values in the <strong>FILESTREAM</strong> columnand providing a default value <strong>of</strong> 0x. This ensures that the <strong>FILESTREAM</strong> cell will alwaysbe associated with a valid file, and can remove some repetitive code from the applicationthat is writing <strong>FILESTREAM</strong> data.Replacing the <strong>FILESTREAM</strong> data completelyWhen the <strong>FILESTREAM</strong> data is to be replaced completely, this is usually done usingthe streaming APIs. A client application can perform a write operation using either theSqlFileStream class (.NET) or the OpenSqlFilestream() Win32 API function. Whenthe <strong>FILESTREAM</strong> data file is opened for write access, the file pointer is at the beginning<strong>of</strong> the file. <strong>The</strong> write operation will write into a new disk file, and the reference on the<strong>FILESTREAM</strong> column will be updated to point to the new file when the file handle is103

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!