Search code examples
sql-server-2008varbinarymax

Is there a tool to load files into varbinary(max) fields?


I was contemplating the creation of a tool to load varbinary(max) fields in a SQL Server 2008 database with files as selected from a open file dialog. Is there any such tool or equivalent that I could use? My SQL server is in a hosted environment where I don't have physical access to the server so loading it with TSQL is not an option.


Solution

  • How about powershell?

    # from: http://sev17.com/2010/05/t-sql-tuesday-006-blobs-filestream-and-powershell/
    #
    $server = "superfly\sqlexpress"
    $database = "Yak"
    $query = "INSERT dbo.FileStore VALUES (@FileData, @FileName)"
    $filepath = "d:\yak.txt"
    $FileName = get-childitem $filepath | select -ExpandProperty Name
    
    $connection=new-object System.Data.SqlClient.SQLConnection
    $connection.ConnectionString="Server={0};Database={1};Integrated Security=True" -f $server,$database
    $command=new-object system.Data.SqlClient.SqlCommand($query,$connection)
    $command.CommandTimeout=120
    $connection.Open()
    
    $fs = new-object System.IO.FileStream($filePath,[System.IO.FileMode]'Open',[System.IO.FileAccess]'Read')
    $buffer = new-object byte[] -ArgumentList $fs.Length
    $fs.Read($buffer, 0, $buffer.Length)
    $fs.Close()
    
    $command.Parameters.Add("@FileData", [System.Data.SqlDbType]"VarBinary", $buffer.Length)
    $command.Parameters["@FileData"].Value = $buffer
    $command.Parameters.Add("@FileName", [System.Data.SqlDbType]"NChar", 50)
    $command.Parameters["@FileName"].Value = $FileName
    $command.ExecuteNonQuery()
    
    $connection.Close()