In C#, I am inserting data into a SQL table. The SQL column is of type varchar(4000)
, so in C# I need to truncate the string if it is too long, so that it can be stored in SQL. To perform the truncation, I need to know the weight of the string when it is added to SQL.
So far I have tried to use the length of the C# string with myString.Lentgh * sizeof(char)
but this solution does not give the right answer, because the encoding may not be the same, so the weight of a character in C# is not the same as in SQL.
I also tried to do a SQL query SELECT LEN(myString)
but this involves doing several queries to get the right truncation, so this solution is very slow.
So is there any way to calculate it directly in C#?