简体   繁体   中英

SQL SERVER: String or binary data would be truncated. nvarchar

I'm trying to insert into the following table:

在此处输入图片说明

but for some reason I cannot insert more than 250 characters into slabel1 field, even though it's size it's 500. Every time this happens I receive the following error:

String or binary data would be truncated. The statement has been terminated.

I do not understand why.

Your results show the length in bytes of the column, not how many characters it can store. The column you are using is an nvarchar column, and so a character will take up 2 bytes instead of 1, so in your case (500 / 2) = 250 characters max.

This will show you the difference, we have two columns, each which can hold 50 characters, but the length of the nvarchar column is 100

CREATE TABLE [#text]
(
  [Text] VARCHAR(50),
  [NText] NVARCHAR(50)
)

SELECT COL_LENGTH( 'tempdb..#Text' , 'Text' ) [Varchar_Length],
       COL_LENGTH( 'tempdb..#Text' , 'NText' ) [NVarchar_Length]


DROP TABLE [#text]

The results are:

Varchar_Length | NVarchar_Length
50             | 100

Because it's NVARCHAR

nchar and nvarchar

nchar [ ( n ) ]

Fixed-length Unicode string data. n defines the string length and must be a value from 1 through 4,000. The storage size is two times n bytes. When the collation code page uses double-byte characters, the storage size is still n bytes. Depending on the string, the storage size of n bytes can be less than the value specified for n. The ISO synonyms for nchar are national char and national character..

nvarchar [ ( n | max ) ]

Variable-length Unicode string data. n defines the string length and can be a value from 1 through 4,000. max indicates that the maximum storage size is 2^31-1 bytes (2 GB). The storage size, in bytes, is two times the actual length of data entered + 2 bytes. The ISO synonyms for nvarchar are national char varying and national character varying.

Try this one to see the differences

DECLARE @text1 NVARCHAR(200)
DECLARE @text2 VARCHAR(200)

SET @text1 = 'aaaaaaaa'
SET @text2 = 'aaaaaaaa'

SELECT LEN(@text1), DATALENGTH(@text1)

SELECT LEN(@text2), DATALENGTH(@text2)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM