当数据中有空格时,Len无法工作

时间:2017-12-14 06:52:12

标签: sql-server

使用下面的代码无效,因为第2列中有空格。 026923102690542625548030(1)
数字和(1)之间需要空格,但我相信还有可以剥离的训练空间。

   select RIGHT([Column 2], len([Column 2]) - 19) AS newcol2, [Column 2] from [dbo].[231]

当我试图显示48030(1)

时,这在newcol2中没有返回任何内容

我尝试用DATALENGTH替换len,这只是给了我一份[第2栏]

***添加了更多信息

当我尝试

    select 
RIGHT([Column 2], len(REPLACE([Column 2],' ','')) - 2) AS newcol2, 
[Column 2] from [dbo].[231]

我得到了结果

newcol2      [Column 2]
(1)          026923102690970425568331 (1)                     
             026923102690970525568331 

我需要newcol2列来说68331(1)和68331 字段类型为nvarchar(50)

尝试以下

    select 
RIGHT([Column 2], len(REPLACE([Column 2],CHAR(10),'')) - 19) AS newcol2, 
[Column 2] from [dbo].[231]

    select 
RIGHT([Column 2], len(REPLACE([Column 2],CHAR(13),'')) - 19) AS newcol2, 
[Column 2] from [dbo].[231]

仍然相同

***添加了解决方案

    WITH CTE
AS
(
    SELECT 
        [Column 2] = LTRIM(RTRIM(REPLACE(REPLACE([Column 2],CHAR(10),''),CHAR(13),'')))
        FROM [dbo].[231]
)
SELECT
     RIGHT([Column 2], len([Column 2]) - 19) AS newcol2,
    [Column 2]
    FROM CTE

1 个答案:

答案 0 :(得分:1)

替换空格后尝试长度

select 
RIGHT([Column 2], len(REPLACE([Column 2],' ','')) - 19) AS newcol2, 
[Column 2] from [dbo].[231]

OR

select 
    RIGHT([Column 2], len(REPLACE([Column 2],' (1)','(1)')) - 19) AS newcol2, 
    [Column 2] from [dbo].[231]

我跑这个时得到了正确的答案

DECLARE @T VARCHAR(50)='026923102690542625548030 (1)'

SELECT
    RIGHT(@T, LEN(@T) - 19) AS newcol2,
    @T

尝试从列中替换CHAR(10)和CHAR(13)并计算len。这可能有用。像这样

WITH CTE
AS
(
    SELECT 
        [Column 2] = LTRIM(RTRIM(REPLACE(REPLACE([Column 2],CHAR(10),''),CHAR(13),'')))
        FROM [dbo].[231]
)
SELECT
    RIGHT([Column 2], len(REPLACE([Column 2],' ','')) - 19) AS newcol2, 
    [Column 2]
    FROM CTE