How can I insert more than 8000 characters in a VARCHAR(MAX) column with ExecuteNonQuery?

依然范特西╮ 提交于 2019-12-01 10:51:38

The issue may not be the storage of the data, it may be the retrieval.

If you are trying to determine whether or not more than 8000 chars were stored in the DB through enterprise manager, then you are out of luck if you just select the contents of the columns and look at the text length: enterprise manager limits the column output.

To determine how much data is actually stored in the column, execute the following query:

SELECT DATALENGTH(Terms) FROM tblTerms

This will tell you how much text was stored.

EDIT:

Another thought just occurred: the enterprise library caches stored procedure parameters in order to improve performance. If you changed the stored procedure after testing with the parameter set to nvarchar(8000), then switch the parameter to nvarchar(max) without resetting the application (if IIS-hosted, then iisreset or dirty web.config), then you will still be using the old stored proc parameter.

REPLICATE returns the input type irrespective of later assignment. It's annoying, but to avoid silent truncation, try:

SET @x = REPLICATE(CONVERT(VARCHAR(MAX), 'a'), 10000);

This is because SQL Server performs the REPLICATE operation before it considers what you're assigning it to or how many characters you're trying to expand it to. It only cares about the input expression to determine what it should return, and if the input is not a max type, it assumes it is meant to fit within 8,000 bytes. This is explained in Books Online:

If string_expression is not of type varchar(max) or nvarchar(max), REPLICATE truncates the return value at 8,000 bytes. To return values greater than 8,000 bytes, string_expression must be explicitly cast to the appropriate large-value data type.

Your sample code can be fixed by doing:

declare @x varchar(max)
set @x = replicate (cast('a' as varchar(max)), 10000)
select @x, len(@x)

You haven't shown the code where you are trying to use ExecutenonQuery. Note that you should use parameters.

using(var con = new SqlConnection(conString))
using(var cmd = new SqlCommand("storedProcedureName", con))
{
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.Add("@text", SqlDbType.NVarChar, -1);
    cmd.Parameters["@text"].Value = yourVeryLongText;
    cmd.ExecuteNonQuery();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!