【问题标题】:T-SQL String Functions: difference between using Left/Right and Substring and strange behaviourT-SQL 字符串函数:使用左/右和子字符串的区别和奇怪的行为
【发布时间】:2011-02-03 04:44:25
【问题描述】:

我正在使用 SQL Server 2008 和 2005 (Express)。我正在尝试从 varchar 字段中提取部分字母数字字符串。

RIGHT(str_field, 3) 产生空值,但SUBSTRING(str_field, LEN(str_field)-2, LEN(str_field)) 给出正确的值。 LEFT(str_field, 7) 给出预期值。是什么赋予了?

我原以为RIGHT(str_field, 3)SUBSTRING(str_field, LEN(str_field)-2, LEN(str_field)) 是等价的表达式。

【问题讨论】:

    标签: sql-server-2005 tsql sql-server-2008


    【解决方案1】:

    你有尾随空格

    RIGHT 会产生空格,但 LEN 会忽略尾随空格

    DECLARE @foo varchar(100)
    SET @foo = 'abc12345def   ' --3 spaces
    
    --right or substring
    SELECT RIGHT(@foo, 3)
    SELECT SUBSTRING(@foo, LEN(@foo)-2, LEN(@foo))
    
    --demonstrate you get spaces
    SELECT REPLACE(RIGHT(@foo, 3), ' ', 'z') --single space
    
    --length differences
    SELECT LEN(@foo), DATALENGTH(@foo)
    
    --solution
    SELECT RIGHT(RTRIM(@foo), 3)
    --or trim your column values before storing
    

    SET ANSI_PADDING

    注意:您不会为非 NULL 输入获得 NULL...

    --only NULL if you send in NULL
    SELECT RIGHT(NULL, 3)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-05-10
      • 2021-04-20
      • 1970-01-01
      • 1970-01-01
      • 2015-09-16
      • 1970-01-01
      相关资源
      最近更新 更多