[英]How do you perform a CASE SENSITIVE nested REPLACE command?
I have a table:我有一张桌子:
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
The list on the left shows the actual table.左边的列表显示了实际的表格。 The list on the right is how I want them to appear in the results.右边的列表是我希望它们出现在结果中的方式。 In order for me to do this, I am using the following nested REPLACE command:为了做到这一点,我使用了以下嵌套的 REPLACE 命令:
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(Building,'__P','(')
,'__p',')')
,'__b',' ')
,'__u','-')
,'__7','&')
,'__d','.') as [Building]
The problem with this is that the "__P" and "__p" are treated the same and the results end up like this:问题在于“__P”和“__p”的处理方式相同,结果是这样的:
Building 10 (Bldg Ten(
D & T (Diagnostic & Treatment(
The right parentheses ")" do not show up.右括号“)”不出现。
I tried using:我尝试使用:
...REPLACE(REPLACE(Building COLLATE SQL_Latin1_General_CP1_CI_AS,'__P','('),'__p',')')...
but it doesn't seem to work in a nested REPLACE query.但它似乎不适用于嵌套的 REPLACE 查询。 I get basically the same results.我得到基本相同的结果。
Is there a way to do this?有没有办法做到这一点?
Use COLLATE SQL_Latin1_General_CP1_CS_AS
(case sensitive):使用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
Output:输出:
╔════════════════════════════════════════════╦══════════════════════════════╗
║ 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 ║
╚════════════════════════════════════════════╩══════════════════════════════╝
Add also one more REPLACE(..., 'n__fa', 'n/a')
or REPLACE(..., '__f', '/')
depending on your needs.根据您的需要REPLACE(..., 'n__fa', 'n/a')
添加一个REPLACE(..., 'n__fa', 'n/a')
或REPLACE(..., '__f', '/')
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.