TSQL in Memory VarBinary to Text File?
With SQL Server 2008, I have a stored procedure that accepts a VarBinary parameter. While the parameter is in memory, I would like to write it to the %temp% directory of the SQL Server.
How can I go from memory blob (it came as a byte[] from a C# app) to text file? The blob does not exist in any disk-resident table.
I am leaning开发者_开发技巧 towards having the TSQL sproc call a CLR stored procedure, which so far looks (mostly) like the below.
Problem #1 is that I think the inputBytes[] is stuck at 8k input size.
Problem #2 is that I can't seem to come up with some decent SQL that passes a varbinary value as a parameter so I can test this within Management Studio or VS DB unit test.
public static void FileWrite( string inputName , byte[] inputBytes )
using (FileStream fileStream = new
FileStream(Environment.GetEnvironmentVariable("TEMP") + "\\" + inputName,
FileMode.OpenOrCreate, FileAccess.Write))
{
using ( BinaryWriter binaryWriter = new BinaryWriter(fileStream))
{
binaryWriter.Write( inputBytes );
}
}
Thanks.
If you have the byte[] in C# code, you could easily write to a file:
http://msdn.microsoft.com/en-us/library/system.io.file.writeallbytes.aspx
Would this work for you?
EDIT: Another idea if you must initiate the file save from SQL Server might be to create a SQL Server CLR Function. This would allow you to execute C# code from SQL Server.
EDIT 2: I did a Google search and found an article on CodeProject. In the article, they are compressing and decompressing blob data. I think the trick here is to use the SqlBytes parameter type vs a plain old byte[]. Below is some (untested) code I came up with after reading the article and your updated question:
using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
using System.IO;
using System.IO.Compression;
public partial class UserDefinedFunctions
{
// Setting function characteristics
[Microsoft.SqlServer.Server.SqlFunction(IsDeterministic=true, DataAccess=DataAccessKind.None)]
public static void fn_WriteToFile(string fileName, SqlBytes blob)
{
if( blob.IsNull || String.IsNullOrEmpty(fileName) )
{
return;
}
String fullFileName = Path.Combine(Environment.GetEnvironmentVariable("TEMP"), fileName);
using( FileStream fileStream = new FileStream(fullFileName, FileMode.OpenOrCreate, FileAccess.Write))
using( BinaryWriter binaryWriter = new BinaryWriter(fileStream) )
{
binaryWriter.Write(blob.Buffer);
}
}
};
Let me know what you think.
精彩评论