我有一张桌子:
Building Building
1__bEast 1 East
1__bSouth 1 South
500__bBldg__d 500 Bldg.
501__bBldg__d 501 Bldg.
B__u1 B-1
B__u2 B-2
B__u2__bWest B-2 West
Building__b10__b__PBldg__bTen__p Building 10 (Bldg Ten)
D__7T__b__PDiagnostic__b__7__bTreatment__p D & T (Diagnostic & Treatment)
n__fa n/a
左侧的列表显示实际的表格。右边的列表是我希望它们出现在结果中的方式。为了让我这样做,我使用以下嵌套的REPLACE命令:
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(Building,'__P','(')
,'__p',')')
,'__b',' ')
,'__u','-')
,'__7','&')
,'__d','.') as [Building]
问题在于“__P”和“__p”被视为相同,结果最终如下:
Building 10 (Bldg Ten(
D & T (Diagnostic & Treatment(
右括号“)”不显示。
我尝试使用:
...REPLACE(REPLACE(Building COLLATE SQL_Latin1_General_CP1_CI_AS,'__P','('),'__p',')')...
但它似乎不适用于嵌套的REPLACE查询。我得到的结果基本相同。
有办法做到这一点吗?
答案 0 :(得分:2)
使用COLLATE SQL_Latin1_General_CP1_CS_AS
(区分大小写):
CREATE TABLE #tab(Building VARCHAR(100));
INSERT INTO #tab
SELECT '1__bEast'
UNION ALL SELECT '1__bSouth'
UNION ALL SELECT '500__bBldg__d'
UNION ALL SELECT '501__bBldg__d'
UNION ALL SELECT 'B__u1'
UNION ALL SELECT 'B__u2'
UNION ALL SELECT 'B__u2__bWest'
UNION ALL SELECT 'Building__b10__b__PBldg__bTen__p'
UNION ALL SELECT 'D__7T__b__PDiagnostic__b__7__bTreatment__p'
UNION ALL SELECT 'n__fa';
SELECT Building,
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(Building COLLATE SQL_Latin1_General_CP1_CS_AS ,'__P','(')
,'__p',')')
,'__b',' ')
,'__u','-')
,'__7','&')
,'__d','.') as [Building]
FROM #tab
的 LiveDemo
强>
输出:
╔════════════════════════════════════════════╦══════════════════════════════╗
║ Buidling ║ Replaced ║
╠════════════════════════════════════════════╬══════════════════════════════╣
║ 1__bEast ║ 1 East ║
║ 1__bSouth ║ 1 South ║
║ 500__bBldg__d ║ 500 Bldg. ║
║ 501__bBldg__d ║ 501 Bldg. ║
║ B__u1 ║ B-1 ║
║ B__u2 ║ B-2 ║
║ B__u2__bWest ║ B-2 West ║
║ Building__b10__b__PBldg__bTen__p ║ Building 10 (Bldg Ten) ║
║ D__7T__b__PDiagnostic__b__7__bTreatment__p ║ D&T (Diagnostic & Treatment) ║
║ n__fa ║ n__fa ║
╚════════════════════════════════════════════╩══════════════════════════════╝
根据您的需要,再添加一个REPLACE(..., 'n__fa', 'n/a')
或REPLACE(..., '__f', '/')
。