
Transact-SQL UPDATETEXT Example
The following sample demonstrates how to write a BLOB in chunks to SQL Server. The sample adds a new record to the Employees table of the Northwind database, including an image of the employee, which is a BLOB. The sample uses the UPDATETEXT function of SQL Server to write the image of the newly added employee to the Photo field in chunks of a specified size.
The UPDATETEXT function requires a pointer to the BLOB field being updated. In this sample, when the new employee record is added, the SQL Server TEXTPTR function is called to return a pointer to the Photo field of the new record. The returned pointer value is passed back as an output parameter. The code in the sample retains this pointer and passes it to UPDATETEXT when appending the chunks of data.
The Transact-SQL used to insert the new employee record and retain the pointer to the Photo field is shown in the following example (where @Identity and @Pointer are identified as output parameters for the SqlCommand).
INSERT INTO Employees (LastName, FirstName, Title, HireDate, ReportsTo, Photo)
Values(@LastName, @FirstName, @Title, @HireDate, @ReportsTo, 0x0)
SELECT @Identity = SCOPE_IDENTITY()
SELECT @Pointer = TEXTPTR(Photo) FROM Employees WHERE EmployeeID = @Identity
Note that an initial value of 0x0 (null) is inserted into the Photo field. This ensures that a pointer value can be retrieved for the Photo field of the newly inserted record. However, the null value will not affect the appended chunks of data.
Having retained a pointer to the Photo field in the newly inserted record, the sample can then append chunks of data to the BLOB field using the UPDATETEXT function of SQL Server. The UPDATETEXT function takes as input the field identifier (Employees.Photo), the pointer to the BLOB field, an offset value that represents the location in the BLOB where the current chunk will be written, and the chunk of data to append. The following code example shows the syntax for the UPDATETEXT function (where @Pointer, @Offset, and @Bytes are identified as input parameters for the SqlCommand).
UPDATETEXT Employees.Photo @Pointer @Offset 0 @Bytes
The offset value is determined by the size of the memory buffer, which you determine based on the needs of your application. A large buffer size will write the BLOB faster, but will use more system memory. This sample uses a rather small buffer size of 128 bytes. The offset value starts at 0 for the first chunk of data, and is incremented by the size of the buffer for each consecutive chunk.