Trying to prefix a string field on a table by using the UPDATE command. For some reason I’m getting the
String or binary data would be truncated.
exception, even though the length of my data would easily fit in the field.
Using SQL Server 2008 R2 Standard Edition and SSMS 2008 R2.
Template: Learner is a nvarchar(60)
Template: Learner is a nvarchar(30) using 60 bytes as shown in sp_help
select LEN('Aaaaaaaa' + LEFT(learner, 52)) myLen from Template order by myLen desc
>>> max len = 31
update Template set learner = 'Aaaaaaaa' + LEFT(learner, 52)
>>> String or binary data would be truncated.
update Template set learner = 'Aaaaaaaa' + LEFT(learner, 52)
>>> String or binary data would be truncated.
update Template set learner = CAST('Aaaaaaaa' + LEFT(learner, 52) AS NVARCHAR(60))
>>> String or binary data would be truncated.
Whereas the following works:
SELECT CAST('Aaaaaaaa' + LEFT(learner, 52) AS NVARCHAR(60)) FROM Template
Thanks for your responses.
Looks like I was fooled by the length value on sp_help and sp_columns. As it’s a NVARCHAR column the length means the length in bytes and not the number of characters. This is because NVARCHAR = Unicode (UTF-16) => 2 Bytes per character.
Looking at the CREATE script revealed the truth. Also the PRECISION field on sp_columns shows the number of characters too.