如果它们全部为零,如何删除前N个特定字符

时间:2015-02-13 16:19:10

标签: sql-server string

我有这种类型的字符串

01/CBA/1234567890
02/ABC/0000969755
06/DEF/0000000756

我想删除零并获得以下输出

01/CBA/1234567890
02/ABC/969755
06/DEF/756

我该怎么做?我虽然关于RIGHT,LEFT,CHARINDEX,SUBSTRING函数的组合,但不知道如何组合它们。

有什么想法吗?

4 个答案:

答案 0 :(得分:1)

您可以使用以下内容:

SUBSTRING(myString, PATINDEX('%[^0]%', myString+'.'), LEN(myString))

答案 1 :(得分:1)

试试这个

方法1

DECLARE @STR VARCHAR(100)= '02/ABC/0000969755'

SELECT SUBSTRING(@STR,0,LEN(@STR) - CHARINDEX('/', REVERSE(@STR)) + 2)+
 CAST(CAST(REVERSE(SUBSTRING(REVERSE(@STR),0,CHARINDEX('/',REVERSE(@STR))))AS INT)AS VARCHAR(20))

方法2

DECLARE @STR VARCHAR(100)= '02/ABC/0000969755'


;WITH CTE AS
(
    -- Convert to rows
    SELECT ROW_NUMBER() OVER(ORDER BY (SELECT 0)) RNO,
    LTRIM(RTRIM(Split.a.value('.', 'VARCHAR(100)'))) 'STRING' 
    FROM  
    (        
         SELECT CAST ('<M>' + REPLACE(@STR, '/', '</M><M>') + '</M>' AS XML) AS Data      
    ) AS A 
    CROSS APPLY Data.nodes ('/M') AS Split(a)
)
,CTE2 AS
(
   -- Convert to int and then varchar
   SELECT RNO,CASE WHEN RNO = 3 THEN CAST(CAST(STRING AS INT)AS VARCHAR(40)) ELSE STRING END STRR
   FROM CTE
)
-- Convert back to / separated values
SELECT  SUBSTRING(
         (SELECT  '/ ' + STRR
          FROM CTE2             
          ORDER BY RNO
          FOR XML PATH('')),2,200000) STRING

答案 2 :(得分:1)

以下查询将为您提供帮助

DECLARE @var VARCHAR(500) = '06/DEF/0000000756'
SELECT 
  LEFT(@var, CHARINDEX('/',@var))  + 
  LEFT(REPLACE(@var, LEFT(@var, CHARINDEX('/',@var)),''), 
      CHARINDEX('/',REPLACE(@var, LEFT(@var, CHARINDEX('/',@var)) ,''))) 
                                   +
 CONVERT(varchar, CONVERT(numeric(18,0),REPLACE(REPLACE(@var,LEFT(@var, 
        CHARINDEX('/',@var)),''),Left(REPLACE(@var,LEFT(@var,
        CHARINDEX('/',@var)) ,''), 
        CHARINDEX('/',REPLACE(@var,LEFT(@var,
        CHARINDEX('/',@var)),''))),'')))

答案 3 :(得分:1)

  

使用左右字符串函数

DECLARE @str varchar(20)='06/DEF/0000000756'
SELECT left(@str,7)+convert(varchar(20),convert(int,right(@str,10)))

enter image description here