如何从表中使用文件名进行BCP查询?

时间:2014-10-24 03:35:19

标签: sql bcp

我正在使用BCP将许多BLOB提取到文件中,并想知道是否有办法使用SQL表中的ID字段为每个文件赋予唯一名称。 这有效:

DECLARE  @Command NVARCHAR(4000)  
SET @Command = 'bcp "SELECT FileData FROM MyDB.dbo.Attachments 
                WHERE Hist_ID = ''00004F13''" 
                queryout "C:\Wha.pdf" -T -c -C RAW -S SERVERNAME -U SA -P pa$$word'  
EXEC xp_cmdshell   @Command

但是为了得到文件名,我试过了:

DECLARE @FileName varchar(50),  
@Command NVARCHAR(4000)  
SET @FileName = Hist_ID+'wha.PDF'  
SET @Command = 'bcp "SELECT FileData FROM MyDB.dbo.Attachments 
                WHERE Hist_ID = ''00004F13''"     queryout'  
SET @Command = @Command + 'C:\' + @FileName + '-T -c -C RAW 
                           -S SERVERNAME -U SA -P pa$$word'  
EXEC xp_cmdshell   @Command

我收到错误:列名“Hist_ID”无效。 有办法做到这一点吗?谢谢你的帮助!

1 个答案:

答案 0 :(得分:2)

试试这个。这是我知道必须一次执行一行的唯一方法。

此代码只打印命令。取消注释xp_cmdshell以使其实际运行。您可能希望先从一个小样本开始(通过限制选择)

DECLARE @Hist_ID VARCHAR(100)
DECLARE @Ext VARCHAR(10)
DECLARE @Command NVARCHAR(4000)  


DECLARE cAttachments CURSOR FOR
SELECT DISTINCT Hist_ID,Extension
FROM MyDB.dbo.Attachments 
ORDER BY Hist_ID

OPEN cAttachments

FETCH NEXT FROM cAttachments
INTO @Hist_ID, @Ext

WHILE @@FETCH_STATUS = 0
BEGIN

    SET @Command = 'bcp "SELECT FileData FROM MyDB.dbo.Attachments 
                WHERE Hist_ID = ''' + @Hist_ID + '''"
                queryout "C:\' + @Hist_ID + '.' + @Ext + '" -T -c -C RAW -S SERVERNAME -U SA -P pa$$word'  

    PRINT @Command

    -- EXEC xp_cmdshell   @Command


    FETCH NEXT FROM cAttachments
    INTO @Hist_ID, @Ext

END

CLOSE cAttachments
DEALLOCATE cAttachments