如何使用sql查询从表中检索图像并将其保存到不同服务器的文件夹中
如何使用sql查询从表中检索图像并将其保存到不同服务器的文件夹中如何使用sql查询从表中检索图像并将其保存到不同服务器的文件夹中,sql,sql-server,Sql,Sql Server,如何使用sql查询从表中检索图像并将其保存到不同服务器的文件夹中 映像以BLOB的形式存储在DB中。不能单独使用SQL Server执行文件系统操作。因此,如果要将存储在SQL Server数据库中的图像保存为文件系统中的文件,请尝试使用C或任何此类前端语言从数据库中检索记录,然后保存到所需位置,您可以使用类似的方法 -- This will create format file, replace [TABLE_NAME_WITH_DATABASE] with your table and [S
映像以BLOB的形式存储在DB中。不能单独使用SQL Server执行文件系统操作。因此,如果要将存储在SQL Server数据库中的图像保存为文件系统中的文件,请尝试使用C或任何此类前端语言从数据库中检索记录,然后保存到所需位置,您可以使用类似的方法
-- This will create format file, replace [TABLE_NAME_WITH_DATABASE] with your table and [SERVERNAME] with your server name
EXEC xp_cmdshell 'bcp [TABLE_NAME_WITH_DATABASE] format null -S [SERVERNAME] -T -n -f c:\Test\PP.fmt'
-- After this step you will see a format file,in that you have to delete all other columns except your image column
-- and run below query.
EXEC xp_cmdshell 'bcp "SELECT Photo FROM Server.Db.Table WHERE PK = 1" queryout C:\Test\ProductPhotoID_69.[IMAGE_EXTENSTION] -S [SERVERNAME] -T -f C:\Test\PP.fmt'
您可以使用PowerShell进行此操作,下面是一个示例:
$connectionString = "Data Source=SERVER;Initial Catalog=DATABASE;pwd=PASSWORD;User ID=USER;"
$sqlCommandText = "SELECT id, Photo, Photo_TypeMime FROM MYTABLE" #query
$saveToDir = "D:\" # output directory
$connection = new-object System.Data.SqlClient.SQLConnection($connectionString)
$command = new-object System.Data.sqlclient.sqlcommand($sqlCommandText,$connection)
$connection.Open()
$bufferSize = 8192 #default value
$buffer = [array]::CreateInstance('Byte', $bufferSize)
$dr = $command.ExecuteReader()
While ($dr.Read())
{
$ext = GetExtFromMimeType($dr.GetString(2)) # create a function to return extention from mime type if you don't have the file name saved in the database
$fs = New-Object System.IO.FileStream($saveToDir + $dr.GetDecimal(0) + $ext), Create, Write #my example id is decimal but you can change it
$bw = New-Object System.IO.BinaryWriter $fs
$start = 0
$received = $dr.GetBytes(1, $start, $buffer, 0, $bufferSize - 1)
While ($received -gt 0)
{
$bw.Write($buffer, 0, $received)
$bw.Flush()
$start += $received
# Read next byte stream
$received = $dr.GetBytes(1, $start, $buffer, 0, $bufferSize - 1)
}
$bw.Close()
$fs.Close()
}
$fs.Dispose()
$dr.Close()
$command.Dispose()
$connection.Close()
您还可以在这里找到更详细的示例:图像如何存储在表中。请同时共享表结构。SET@imageVar=从表中选择列,其中条件插入表SET value=@imageVar;。但是,如果没有表架构等,就不可能100%帮助您。如果您的解决方案与另一种语言配对,这将变得非常简单。我可以将映像保存在同一台服务器上。但我想将其保存在另一台服务器上。有什么方法可以做到这一点吗?这将在远程服务器上执行,仅当您希望将映像保存到承载sql server实例的服务器上时,此操作才起作用