I am trying to export a fairly large number of image files, stored internally in an SQL database as binary data.
Being fairly new to writing stored procedures in SQ
Here is my final working procedure and format file. I was not able to find the finer details of BCP commands, permision settings and format file layouts in one place, so maybe this will be of use to someone.
CREATE PROCEDURE [dbo].[ImgExport]
@OutputFilePath VARCHAR(500) = 'C:\SQLTest\ '
AS
BEGIN
DECLARE @totrow int
DECLARE @currow int
DECLARE @result int
DECLARE @nsql nvarchar(4000)
DECLARE @sqlStatements table (ID int IDENTITY(1, 1), SqlStatement varchar(max))
INSERT
INTO @sqlStatements
SELECT 'BCP "SELECT Photograph_Data FROM [ALBSCH_Trial].[dbo].[Photograph] WHERE Photograph_ID = '''
+ CAST(Photograph_ID AS VARCHAR(500)) + '''" queryout ' + @OutputFilePath
+ CAST(Photograph_ID AS VARCHAR(500)) + '.jpg -S localhost\SQLEXPRESS2008 -T -f C:\SQLTest\Images.fmt'
FROM dbo.Photograph
SET @totrow = @@ROWCOUNT
SET @currow = 1
WHILE @totrow > 0 and @currow <= @totrow
BEGIN
SELECT @nsql = SqlStatement
FROM @sqlStatements
WHERE ID = @currow
EXEC @result = xp_cmdshell @nsql
SET @currow = @currow + 1
END
END
Format file:
9.0
1
1 SQLBINARY 0 0 "\t" 1 Photograph_Data ""
I hope that helps somebody.