因此,我的数据当前以客户的名字为后缀。可能是:MISS | MRS | MISS | MR | DR | MS | JT | CHD | CHLD | DEAN | REV | MRI | EARL | DRI | DEAN | MSI。
我正试图摆脱结尾处的后缀。
以下是数据示例
名字:
RUTH ANNE MRS
CHRISTOPHER MR
这是我编写的代码,但是我的代码只删除了一个字母,因此露丝·安妮(Ruth Anne MRS)会显示为RUTH ANNE MR
REPLACE(SUBSTRING(First_Name, CHARINDEX('MISS|MRS|MISS|MR|DR|MS|JT|CHD|CHLD|DEAN|REV|MRI|EARL|DRI|DEAN|MSI', First_Name), LEN(First_Name)), 'MISS|MRS|MISS|MR|DR|MS|JT|CHD|CHLD|DEAN|REV|MRI|EARL|DRI|DEAN|MSI', ' ')
答案 0 :(得分:0)
编写SQL:
获取REVERSE字符串中第一个空格字符的CHARINDEX,
检查该子字符串是否适合后缀模式之一,
如果是这样,则返回原始字符串(使用LEFT)缩短了该子字符串的长度。
答案 1 :(得分:0)
您可以使用以下查询删除结尾的后缀
DECLARE @string VARCHAR(4000);
SET @string =空格(1)+'RUTH ANNE MRS';
要删除(单词)
AS(
选择'MISS'COLLATE SQL_LATIN1_GENERAL_CP1_CI_AS UNION ALL
选择'MRS'COLLATE SQL_LATIN1_GENERAL_CP1_CI_AS UNION ALL
选择'MISS'COLLATE SQL_LATIN1_GENERAL_CP1_CI_AS UNION ALL
选择'MR'COLLATE SQL_LATIN1_GENERAL_CP1_CI_AS UNION ALL
选择'DR'COLLATE SQL_LATIN1_GENERAL_CP1_CI_AS UNION ALL
选择'MS'COLLATE SQL_LATIN1_GENERAL_CP1_CI_AS UNION ALL
选择'JT'COLLATE SQL_LATIN1_GENERAL_CP1_CI_AS UNION ALL
SELECT'CHD'COLLATE SQL_LATIN1_GENERAL_CP1_CI_AS UNION ALL
SELECT'CHLD'COLLATE SQL_LATIN1_GENERAL_CP1_CI_AS UNION ALL
选择'DEAN'COLLATE SQL_LATIN1_GENERAL_CP1_CI_AS UNION ALL
SELECT'REV'COLLATE SQL_LATIN1_GENERAL_CP1_CI_AS UNION ALL
选择'MRI'COLLATE SQL_LATIN1_GENERAL_CP1_CI_AS UNION ALL
SELECT'EARL'COLLATE SQL_LATIN1_GENERAL_CP1_CI_AS UNION ALL
选择'DRI'COLLATE SQL_LATIN1_GENERAL_CP1_CI_AS UNION ALL
SELECT'DEAN'COLLATE SQL_LATIN1_GENERAL_CP1_CI_AS UNION ALL
选择'MSI'COLLATE SQL_LATIN1_GENERAL_CP1_CI_AS
)
SELECT @string =
更换
(
@string COLLATE SQL_LATIN1_GENERAL_CP1_CI_AS,
ToRemove.word收集SQL_LATIN1_GENERAL_CP1_CI_AS,
空格(1)收集SQL_LATIN1_GENERAL_CP1_CI_AS
)
从到删除
CHARINDEX在哪里
(
ToRemove.word收集SQL_LATIN1_GENERAL_CP1_CI_AS,
@string COLLATE SQL_LATIN1_GENERAL_CP1_CI_AS
)> 0;
SELECT @string;
答案 2 :(得分:0)
如果将标题存储到表中,则可以通过单个SELECT来完成
准备测试数据
CREATE TABLE #titles (title nvarchar(10));
INSERT INTO #titles (title) VALUES ('M.'), ('Mme'), ('Mlle');
CREATE TABLE #data (fullname nvarchar(100));
INSERT INTO #data (fullname) VALUES
('John Doe M.'),
('Mary Jones Mme'),
('Doctor Who Mme'),
('Leia Organa Mlle')
查询
SELECT
d.fullname,
SUBSTRING(d.fullname, 1, LEN(d.fullname) - LEN(t.title)) AS new_fullname,
SUBSTRING(d.fullname, LEN(d.fullname) - LEN(t.title) + 1, LEN(t.title)) AS found_title
FROM #data d LEFT JOIN #titles t ON d.fullname LIKE '%' + t.title
结果
fullname new_fullname found_title
------------------------------ ------------------------------ ------------------------------
John Doe M. John Doe M.
Mary Jones Mme Mary Jones Mme
Doctor Who Mme Doctor Who Mme
Leia Organa Mlle Leia Organa Mlle