How to export image field to file?

后端 未结 4 1036
独厮守ぢ
独厮守ぢ 2020-11-29 06:48

I am using Microsoft SQL Server Management Studio to connect to a database. In it I\'ve got a table, one column of which is an Image column containing file data. Another col

4条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-29 07:29

    From mkader at codeproject:

    EXEC sp_configure 'show advanced options', 1;  
    GO  
    RECONFIGURE;  
    GO
    EXEC sp_configure 'xp_cmdshell',1  
    GO  
    RECONFIGURE;  
    GO
    

    Then dump a format file:

    Declare @sql varchar(500)
    SET @sql = 'bcp DBName.dbo.tblTableName format nul -T -n -f C:\testblob.fmt -S ' + @@SERVERNAME
    select @sql 
    EXEC master.dbo.xp_CmdShell @sql 
    

    My format file looked like this:

    10.0
    12
    1       SQLINT              0       4       ""   1     my_tablecol_id                                  ""
    2       SQLINT              1       4       ""   2     my_tablecol0                                   ""
    3       SQLCHAR             2       256     ""   3     my_tablecol1                                SQL_Latin1_General_CP1_CI_AS
    4       SQLCHAR             2       256     ""   4     my_tablecol2                                SQL_Latin1_General_CP1_CI_AS
    5       SQLCHAR             2       256     ""   5     my_tablecol3                         SQL_Latin1_General_CP1_CI_AS
    6       SQLCHAR             2       2048    ""   6     my_tablecol4                                SQL_Latin1_General_CP1_CI_AS
    7       SQLIMAGE            4       0       ""   7     my_imagecol                                     ""
    8       SQLCHAR             2       2048    ""   8     my_tablecol6                            SQL_Latin1_General_CP1_CI_AS
    9       SQLINT              1       4       ""   9     my_tablecol7                                      ""
    10      SQLINT              1       4       ""   10    my_tablecol8                                    ""
    11      SQLINT              1       4       ""   11    my_tablecol9                               ""
    12      SQLBIT              1       1       ""   12    my_tablecol10                             ""
    

    I then edited the format file like so:

    10.0
    1
    1       SQLIMAGE            0       0       ""   1     my_imagecol                                     ""
    

    And then ran this SQL in SSMS:

    Declare @mynum int
    Declare @sql varchar(500)
    SET @mynum = 49 -- something meaningful only to me
    SET @sql = 'BCP "SELECT my_imagecol FROM DBName.dbo.tblTableName where my_tablecol_id=@mynum" QUERYOUT C:\myfilename.docx -T -fC:\testblob.fmt -S ' + @@SERVERNAME
    EXEC master.dbo.xp_CmdShell @sql
    

    This worked really well, any kind of data in the image column works.

提交回复
热议问题