从列中删除字符串组合

时间:2013-06-14 20:10:51

标签: sql sql-server string logic

我今天早些时候曾问过一个类似的问题,但我发现自从我做了一些假设以来,我的逻辑中存在一些缺陷。

我要做的是消除某些单词出现在字符串中......我创建了一个包含一些示例的表格以便于使用

create TABLE #BrokerNameT (BrokerName varchar(100))

INSERT INTO #BrokerNameT (BrokerName)
VALUES ('Morgan Stanley Co Cash'),
       ('Citi Group Algo Cash'),
       ('JP Morgan Algo'), ('JP Morgan Cash')


SELECT 
   CASE WHEN BrokerName LIKE '%CASH%' 
          THEN RTRIM(LTRIM(SUBSTRING(BrokerName, 1, CHARINDEX('Cash', BrokerName)-1)))
        WHEN BrokerName LIKE '%ALGO%' 
          THEN RTRIM(LTRIM(SUBSTRING(BrokerName, 1, CHARINDEX('algo', BrokerName)-1)))
        WHEN BrokerName LIKE '%Prog%' 
          THEN RTRIM(LTRIM(SUBSTRING(BrokerName, 1, CHARINDEX('prog', BrokerName)-1)))
        WHEN BrokerName LIKE '%BSE%' 
          THEN RTRIM(LTRIM(SUBSTRING(BrokerName, 1, CHARINDEX('bse', BrokerName)-1)))
        WHEN BrokerName LIKE '%FX%' 
          THEN RTRIM(LTRIM(SUBSTRING(BrokerName, 1, CHARINDEX('fx', BrokerName)-1)))
        WHEN BrokerName LIKE '%OTC%' 
          THEN RTRIM(LTRIM(SUBSTRING(BrokerName, 1, CHARINDEX('otc', BrokerName)-1)))
        ELSE '' 
    END
FROM #BrokerNameT

drop table #BrokerNameT

正如您所看到的,我不希望在我的专栏中显示一系列单词。这个查询逻辑的问题在于,如果它有两个单词不允许:让我们说'花旗集团Algo现金';它会在找到CASH时读取CASE逻辑并仍然保持“算法” - 如果你运行该查询,你会看到我的意思......

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

你试过了吗?

create TABLE #BrokerNameT (BrokerName varchar(100))
INSERT INTO #BrokerNameT (BrokerName) VALUES('Morgan Stanley Co Cash')
INSERT INTO #BrokerNameT (BrokerName) VALUES('Citi Group Algo Cash')
INSERT INTO #BrokerNameT (BrokerName) VALUES('JP Morgan Algo')
INSERT INTO #BrokerNameT (BrokerName) VALUES('JP Morgan Cash')

select
         replace(replace(replace(replace(replace(replace(BrokerName,'CASH',''),'ALGO',''),'Prog',''),'bse',''),'FX',''),'OTC','')
from #BrokerNameT

drop table #BrokerNameT

为您不想包含的每个单词添加新的替换。