日期:2014-05-18  浏览次数:20516 次

字符分段和加“-”问题
SQL原数据ZHH:201201123456, 2012TAIWAN123456
分段字符DQDM:01, TAIWAN
固定字段:2012 代表年份,到了明年则为2013 

要求结果为:2012-01-123456,2012-TAIWAN-123456

------解决方案--------------------
SQL code

--格式固定 前4 后6
WITH t AS
(
    SELECT '201201123456' AS ZHH UNION
    SELECT '2012TAIWAN123456'
)

SELECT STUFF(REVERSE(STUFF(REVERSE(ZHH),7,0,'-')),5,0,'-')
FROM t
GO
--前固定,后不固定
WITH t AS
(
    SELECT '201201123456' AS ZHH UNION
    SELECT '2012TAIWAN123456'
)
SELECT CASE WHEN CHARINDEX('TAIWAN',ZHH) > 0 THEN REPLACE(ZHH,'TAIWAN','-TAIWAN-')
            ELSE STUFF(STUFF(ZHH,5,0,'-'),8,0,'-') END AS ZHH
FROM t

ZHH
2012-01-123456
2012-TAIWAN-123456

------解决方案--------------------

SQL code
SELECT
 CASE WHEN CHARINDEX('TAIWAN',ZHH) > 0 
 THEN REPLACE(ZHH,'TAIWAN','-TAIWAN-')
 ELSE STUFF(STUFF(ZHH,5,0,'-'),8,0,'-') END AS ZHH
FROM TB

------解决方案--------------------
SQL code
DECLARE @t TABLE
    (
      G_ZHH VARCHAR(50) ,
      DQDM VARCHAR(10)
    )      
INSERT  @t
        SELECT  '201201123456' ,
                '01'
        UNION ALL
        SELECT  '2012TAIWAN123456' ,
                'TAIWAN'
        UNION ALL
        SELECT  '2012NL1234' ,
                'NL'
        UNION ALL
        SELECT  '2012AU12345' ,
                'AU'
        UNION ALL
        SELECT  '2012221234567' ,
                '22'        
SELECT  * ,
        [OUTPUT] = STUFF(STUFF(G_ZHH, CHARINDEX(DQDM, G_ZHH, 5), 0, '-'),
                         CHARINDEX(DQDM, G_ZHH, 5) + LEN(DQDM) + 1, 0, '-')
FROM    @t
  /*
  G_ZHH                                              DQDM       OUTPUT
-------------------------------------------------- ---------- ----------------------------------------------------------------------------------------------------------------
201201123456                                       01         2012-01-123456
2012TAIWAN123456                                   TAIWAN     2012-TAIWAN-123456
2012NL1234                                         NL         2012-NL-1234
2012AU12345                                        AU         2012-AU-12345
2012221234567                                      22         2012-22-1234567

(5 行受影响)
  */