sql - How can I replace multiple words of a string in SQL
问题描述
Is it possible to replace multiple words in a string in sql without using multiple replace functions?
For example I have a string where I need to replace word 'POLYESTER' with 'POLY' , 'COTTON' with 'CTN', 'GRAPHIC' with 'GRPHC' etc in order to keep the string length at a max of say 30 without much loosing the readability of contents in it(can't use substring to limit chars since it can trim the end meaningful parts of string completely). So we decided to short some keywords like above.
Current query I have used :
SELECT
REPLACE(REPLACE('**Some string value **COTTON **Some string value ** POLYESTER', 'POLYESTER', 'POLY'), 'COTTON', 'CTN')
If I have 10 keywords like this, what will be the best way to achieve the result other than using multiple replace function. I am using SQL Server 2012.
解决方案
考虑到 sql server 是您唯一的工具(不是 ac# 或其他应用程序),作为一种工作方法;使用临时表或持久表来存储替换选项。
IF OBJECT_ID('tempdb..#tmp') IS NOT NULL
DROP TABLE #tmp
CREATE TABLE #tmp (
fromText VARCHAR(16),
toText VARCHAR(16)
);
INSERT INTO #tmp (fromText, toText)
VALUES
('POLYESTER', 'POLY'),
('COTTON', 'CTN'),
('GRAPHIC', 'GRPHC')
DECLARE @someValue AS NVARCHAR(MAX) =
'**Some string value **COTTON **Some string value ** POLYESTER';
SELECT @someValue = REPLACE(@someValue, fromText, toText) FROM #tmp;
PRINT @someValue
结果是:**一些字符串值**CTN **一些字符串值** POLY。
推荐阅读
- python - 是否有一种安全且不受欺骗的方式来检测文件类型?
- laravel - 如何使用 Laravel 和 Nuxtjs 进行身份验证,包括登录、注销和密码重置?
- python - python中的SQL代码-双索引数据透视表计数
- android - kotlin android nav graph go back 导致重新创建旧片段
- python - 通过分隔符拆分熊猫列,行中有两种不同的大小
- c# - Using WIA to scan a doc, but the list doesn't show scanner's wirelessly connected to my network
- wordpress - WordPress wrong Redirect
- reactjs - 'withAlert' is showing "Objects are not valid as React Child" Error
- web-scraping - Scrape the text inside a script tag using jsoup on a website
- mysql - Is a self join no different than joining 2 different tables, in terms of performance