Kihtrak J
Kihtrak J

Reputation: 132

Does the LEN() function internally apply TRIM()?

Dooes the SQL LEN() function internally TRIM() the data prior to calculating length of the string?

Example:

DECLARE @a VARCHAR(MAX), @b VARCHAR(MAX)
SET @a = '12345 '
SET @b = '12345 7'

SELECT @a, LEN(@a)
-- 12345    5

SELECT @b, LEN(@b)
-- 12345 7  7

Both @a and @b have 7 characters. @a has 5 numeral characters and two spaces at the end.

When copying both the results from the Results window, I can see that both variables have a length of 7 chars. But when trying to find the length of the variables using LEN() it differs. The same thing happens while storing data in a table with a varchar column.

Upvotes: 1

Views: 3302

Answers (3)

Olivier Jacot-Descombes
Olivier Jacot-Descombes

Reputation: 112402

LEN excludes trailing blanks.

I would use

LEN(REPLACE(expr, ' ', '_'))

This should work with varchar and nvarchar and also with strings containing special unicode control characters. The DATALENGTH function suggested at other places will not yield the correct result in all cases.

You could also use

LEN(expr + '_') - 1

But the resulting string might exceed the maximum text length in some cases.

Upvotes: 1

D Stanley
D Stanley

Reputation: 152566

It doesn't "trim" the source per se (meaning it doesn't alter it) - but it does exclude training blanks:

From the documentation:

Returns the number of characters of the specified string expression, excluding trailing blanks.

Upvotes: 0

huMpty duMpty
huMpty duMpty

Reputation: 14460

It excludes the trailing blanks

According to LEN (Transact-SQL)

"Returns the number of characters of the specified string expression, excluding trailing blanks."

Also similar questions about

Why does t-sql's LEN() function ignore the trailing spaces?

LEN function not including trailing spaces in SQL Server

Upvotes: 5

Related Questions