Question

We have a strange problem using SqlCommand to insert data into a SQL Server database. If we try to insert a large text into the column konnotiz1, the text is being truncated after 43245 characters. For some reason I don't understand the real application code creates 42909 characters.

Here's a screenshot of the column properties page:

SQL-Server Management Studio propertypage

The following code causes the problem:

static void Test()
{
    using (System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection(getConString()))
    {
        con.Open();
        System.Data.SqlClient.SqlCommand cmd = con.CreateCommand();
        cmd.CommandText = "Insert into kontakte (konlfdnr, konNotiz1) values (@konlfdnr, @konNotiz1)";
        cmd.CommandType = CommandType.Text;
        cmd.CommandTimeout = 60;

        // you can ignore this param, it's owner pk-column. 
        System.Data.SqlClient.SqlParameter param = cmd.Parameters.Add("@konlfdnr", SqlDbType.Char, 10);

        // better don't ask why we have to pad this... ;) 
        param.Value = "1".PadLeft(10);
        param.Direction = ParameterDirection.Input;

        param = cmd.Parameters.Add("@konNotiz1", SqlDbType.Text);
        param.Direction = ParameterDirection.Input;
        param.Value = getParamValue();

        cmd.ExecuteNonQuery();
        con.Close();
    }
}

private static string getParamValue()
{
     // my Textfile has something about 300000 characters. It's a html code from a mail.
     return System.IO.File.ReadAllText("C:\\Temp\\insert.txt");
}

private static string getConString()
{ 
    return @"Data Source=NB-JH1\SQLEXPRESS;Initial Catalog=Testsystem_Local;Integrated Security=True;Encrypt=True;TrustServerCertificate=True;Pooling=True;MultipleActiveResultSets=True;
}

Has anyone an idea, why the text is being truncated and how we can get this working?

Was it helpful?

Solution

Your problem would seem to be a limit in SQL Server Management Studio, not in the database. Here is a bug report on the problem, which claims that the bug has been fixed in the most recent versions (I don't know if this is true). There are work-arounds, as suggested here. I have not personally tried them.

You should test the length by using the len() function (or something similar). This will let you know if all the data is there.

I have worked with very long strings in the database, passing them back and forth between tables, variables, and stored procedures so the database can handle the strings. The problem is in the interface that fetches them.

OTHER TIPS

First, Text is an obsolete sql data type. Use varchar(max) instead. I would try to change the field's type, and the parameter's type.

This would not certainly fix the problem - but it's a good possibility to eliminate (that this what's causing the problem), and it's a good practice too (not to use a deprecated feature)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top