日期:2014-05-18 浏览次数:20516 次
--格式固定 前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
------解决方案--------------------
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
------解决方案--------------------
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 行受影响) */