I can not understand where is my mistake.
I am trying to loop through the table and deliver PDF file that stored in image
datatype to a particular location.
I wrote the cursor, but it gives me a syntax error next to '+'
CREATE TABLE #tblPolicyForms
(
FormID INT NOT NULL,
PDF VARBINARY(MAX) NULL,
PDF_FIlename VARCHAR(MAX)
)
INSERT INTO #tblPolicyForms
SELECT
FormID, PDF, PDF_FileName
FROM
[dbo].[tblPolicyForms]
WHERE
FormID IN (19, 20, 21, 22)
--select * from #tblPolicyForms
DECLARE @FormID varchar(4);
DECLARE @FileName VARCHAR(200);
DECLARE FormID_cursor CURSOR FOR
SELECT
FormID, PDF_FIlename
FROM
#tblPolicyForms
WHERE
FormID IN (19, 20, 21, 22)
--where whatever conditions you need to get the FormIDs you want to use
OPEN FormID_cursor
FETCH NEXT FROM FormID_cursor INTO @FormID, @FileName
WHILE @@FETCH_STATUS = 0
BEGIN
EXEC master.dbo.xp_cmdshell 'BCP "SELECT PDF FROM [MEJAMES].[dbo].tblPolicyForms " queryout "C:\Users\oserdyuk\Documents\ExportDir\'+@FileName+'" -T -N'
FETCH NEXT FROM FormID_cursor INTO @FormID, @FileName
END
CLOSE FormID_cursor
DEALLOCATE FormID_cursor
Use variable:
DECLARE @cmd NVARCHAR(MAX) = N'BCP "SELECT PDF FROM [MEJAMES].[dbo].tblPolicyForms " queryout "C:\Users\oserdyuk\Documents\ExportDir\'+@FileName+'" -T -N';
EXEC master.dbo.xp_cmdshell @cmd;
As from doc EXEC:
{ value
| @variable [ OUTPUT ]
| [ DEFAULT ]
}
So you could only pass value (literal), variable or default. In your example with +
you are trying to pass expression which causes error.
Note: It is a good practice to end each statement with semicolon.