Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I insert a large text value into SQL Server from ASP.net without having the whole file in memory on the webserver?

Tags:

c#

sql-server

As it says in the question, given a large text file, how can I get its contents into a nvarchar(max) column in sql server without loading the entire file contents into memory (either to build a dynamic sql statement or as a SP parameter)?

My best solution so far is to insert a row with an empty value and then in a loop run updates appending chunks of the data each time in a transaction. Is there a better way other than copying the file to the database server and using BCP? Some way to stream the data over?

like image 539
powlette Avatar asked Jul 25 '13 18:07

powlette


People also ask

How do I store large amounts of text in SQL?

If you want to store large amounts of text in a SQL database, then you want to use either a varchar(max) or a nvarchar(max) column to store that data. In case you don't know the difference, nvarchar will support Unicode characters.

Can SQL Server use more than max memory?

The default value allows SQL Server to use as much as the memory required. It might consume almost all OS memory that might raise a server performance issue. The buffer cache comprises the following components: Database page cache.


1 Answers

As of .net4.5 SqlParameters support TextReader https://msdn.microsoft.com/en-us/library/hh556234(v=vs.110).aspx

using (SqlConnection conn = new SqlConnection(connection_string))
using (SqlCommand cmd = conn.CreateCommand())
using (FileStream file = File.OpenRead(@"C:\temp\bigtextfile.txt"))
{
    cmd.CommandText = "INSERT INTO RandomTable (TextBlob) VALUES (@text)";
    cmd.Parameters.Add("@text", System.Data.SqlDbType.NVarChar, -1).Value = file;
    conn.Open();
    cmd.ExecuteNonQuery();
}
like image 121
Lorentz Vedeler Avatar answered Oct 06 '22 00:10

Lorentz Vedeler