You can read the file in small pieces and add them to the data column.
IDENTITY (), UPDATE
, IDENTITY
:
CREATE TABLE [dbo].[table1](
[ID] [int] IDENTITY(1,1) PRIMARY KEY NOT NULL,
[Data] [varbinary](max) NULL,
)
# /
private const string C_SqlConnectionString = @"Server=SERVERNAME;Database=DBNAME;Trusted_Connection=yes;";
private const int C_FileChunkSizeBytes = 1024 * 1024;
private static void storeFile(string filepath)
{
using (FileStream fs = File.Open(filepath, FileMode.Open))
{
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = C_SqlConnectionString;
conn.Open();
SqlCommand command = new SqlCommand("BEGIN TRAN", conn);
command.ExecuteNonQuery();
var pos = 0;
byte[] fileBytes = null;
int sqlRowId = 0;
while (pos < fs.Length)
{
var bytesToRead = pos + C_FileChunkSizeBytes < fs.Length
? C_FileChunkSizeBytes
: (int)(fs.Length - pos);
fileBytes = new byte[bytesToRead];
fs.Read(fileBytes, 0, bytesToRead);
var varbinary = new SqlParameter("0", System.Data.SqlDbType.VarBinary, -1);
varbinary.Value = fileBytes;
if (pos == 0)
{
command = new SqlCommand("INSERT INTO [dbo].[table1] WITH(HOLDLOCK) VALUES(@0)", conn);
command.Parameters.Add(varbinary);
command.ExecuteNonQuery();
command = new SqlCommand("SELECT @@IDENTITY", conn);
sqlRowId = Convert.ToInt32(command.ExecuteScalar());
}
else
{
command = new SqlCommand("UPDATE [dbo].[table1] SET [Data] = [Data] + @0 WHERE [ID] = @1", conn);
command.Parameters.Add(varbinary);
command.Parameters.Add(new SqlParameter("1", System.Data.SqlDbType.Int)).Value = sqlRowId;
command.ExecuteNonQuery();
}
pos += bytesToRead;
}
command = new SqlCommand("COMMIT TRAN", conn);
command.ExecuteNonQuery();
conn.Close();
}
}
}
# while
, , pos += bytesToRead;
.
, , SQL:
SELECT *
,LEN([Data]) AS [Length]
FROM [dbo].[table1] WITH(NOLOCK)
NOLOCK
. LEN([Data])
, while
.