如何在字母数字字符串的中间插入连字符?

时间:2014-05-14 15:24:29

标签: sql oracle oracle11g

我的查询当前生成的输出Part Number为一个值:

SELECT UPPER(PartNumber)AS "Part Number",
    INITCAP(PartDesc)AS "Description"
FROM Part 
WHERE UnitPrice*UnitsOnHand <1000
ORDER BY PartDesc DESC;

Part Number Description                            
----------- ----------------------------------------
BA74        Baseball Bat                             
CA14        Skillet - 12 Inch                        
AZ52        Roller Skates                            

结果应该仍然是2列,但已修改:

Part Number Description                            
----------- ----------------------------------------
BA-74       Baseball Bat                             
CA-14       Skillet - 12 Inch                        
AZ-52       Roller Skates                            

Part Number将始终包含字母/数字字符,Description只是alpha。我需要做的是在字母和数字字符之间插入一个连字符。它们将始终是字母/数字永远不会改变。

1 个答案:

答案 0 :(得分:0)

问题仍然是缺少一些细节,但是如果我的模式正确,并且你想用连字符将第一个字母字符块与其他所有字符分开,你可以使用一对正则表达式和字符串级联:

SELECT UPPER(
      REGEXP_SUBSTR(PartNumber, '[[:alpha:]]+')
      ||'-'||
      REGEXP_SUBSTR(PartNumber, '[^[:alpha:]]+.*')
    ) AS "Part Number",
    INITCAP(PartDesc)AS "Description"
FROM Part 
WHERE UnitPrice*UnitsOnHand <1000
ORDER BY PartDesc DESC;

Part Number           Description                  
--------------------- ------------------------------
CA-14                 Skillet - 12 Inch              
AZ-52                 Roller Skates                  
BA-74                 Baseball Bat                   

这将适用于更复杂的值,只要零件号始终以字符开头:

WITH Part AS (
    SELECT 'b9a74' AS PartNumber, 'baseball BAT' AS PartDesc,
        20 AS UnitPrice, 20 AS UnitsOnHand FROM DUAL
    UNION ALL SELECT 'ca14a1', 'sKiLlEt - 12 iNCH', 20, 20 FROM DUAL
    UNION ALL SELECT 'aza52', 'roller sKaTeS', 20, 20 FROM DUAL
)
SELECT UPPER(
      REGEXP_SUBSTR(PartNumber, '[[:alpha:]]+')
      ||'-'||
      REGEXP_SUBSTR(PartNumber, '[^[:alpha:]]+.*')
    ) AS "Part Number",
    INITCAP(PartDesc)AS "Description"
FROM Part 
WHERE UnitPrice*UnitsOnHand <1000
ORDER BY PartDesc DESC;

Part Number   Description     
------------- -----------------
CA-14A1       Skillet - 12 Inch 
AZA-52        Roller Skates     
B-9A74        Baseball Bat      

但请注意,它总是插入一个连字符,这似乎是你想要的;它不会将所有字符和数字组分开(例如B9A74B-9-A-74)。它只是在第一个非alpha字符前面加一个连字符。