为什么 t-sql 的 LEN() 函数会忽略尾随空格? [英] Why does t-sql's LEN() function ignore the trailing spaces?

查看:33
本文介绍了为什么 t-sql 的 LEN() 函数会忽略尾随空格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

MSDN 上的 LEN() 函数说明:返回指定字符串表达式的字符数,不包括尾随空格.

Description of LEN() function on MSDN : Returns the number of characters of the specified string expression, excluding trailing blanks.

为什么 LEN() 函数设计为以这种方式工作?这种行为解决了什么问题?

Why was the LEN() function designed to work this way? What problem does this behaviour solve?

相关:

推荐答案

它修复了由于数据类型长度导致的字符串自动填充.考虑以下几点:

It fixes the automatic padding of strings due to the data type length. Consider the following:

DECLARE @Test CHAR(10), @Test2 CHAR(10)
SET @Test = 'test'
SET @Test2 = 'Test2'
SELECT  LEN(@Test), LEN(@Test + '_') - 1, LEN(@Test2), LEN(@Test2 + '_') - 1

这将分别返回 4、10、5 和 10.即使@Test 没有使用尾随空格,它仍然保持其长度为 10.如果 LEN 没有修剪尾随空格,则 LEN(@test)LEN(@Test2) 将是相同的.人们通常想知道有意义数据的长度,而不是自动填充的长度,因此 LEN 会删除尾随空白.有一些解决方法/替代方案,这不是必需的行为.

This will return 4, 10, 5 and 10 respectively. Even though no trailing spaces were used for @Test, it still maintains its length of 10. If LEN did not trim the trailing spaces then LEN(@test) and LEN(@Test2) would be the same. More often than not people will want to know the length of the meaningful data, and not the length of the automatic padding so LEN removes trailing blanks. There are workarounds/alternatives where this is not the required behaviour.

这篇关于为什么 t-sql 的 LEN() 函数会忽略尾随空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆