sql - 与字符串操作有关
问题描述
我有一个作物表,其中包含一个作物名称列,例如水果和坚果、蔬菜和瓜类。我必须使用 T-SQL 并删除“和”插入带下划线的空格,并在前面添加文本crop.groups。例如 Fruit and Nuts 将变为crop.groups.fruit_nuts。我必须在 SQL 中为所有作物一起做这些。当我们运行查询时,应该生成一个带有这些转换的单独列。我还必须创建一个对我执行所有这些操作的函数。
我的功能:
CREATE function dbo.translationkey_v10
(
@column_name nchar(15)
)
returns nvarchar(1000)
as
begin
DECLARE @numletters int;
DECLARE @counter int;
DECLARE @str nvarchar(6);
DECLARE @newcolumn_name nvarchar(50)
SET @numletters = LEN(@column_name);
SET @counter = 1;
SET @newcolumn_name = '';
WHILE @counter <= @numletters
BEGIN
-- a. read next character:
----------------------------------------------------------------
SET @str = LOWER(SUBSTRING(@column_name, @counter, 1));
-- b. search for and in the string 'and':
----------------------------------------------------------------
IF (@str LIKE '%and%')
BEGIN
SET @str = REPLACE(@str,' and','')
END
-- c. check for space:
----------------------------------------------------------------
IF UNICODE(@str) = 32
BEGIN
SET @str = '_';
END
SET @newcolumn_name = @newcolumn_name + @str;
SET @counter = @counter + 1;
END
RETURN CONCAT('crop.groups.',@newcolumn_name)
END
样本数据
作物名称:饮料和香料作物
翻译输出:crops.group.beverages_spice_crops
解决方案
这看起来很简单,使用replace
:
select cropname, Concat('crop.groups.', Replace(cropname, ' and ','_'))
from crop
推荐阅读
- amazon-web-services - 我可以暂停/冻结 AWS EC2 专用主机以降低成本吗?
- php - 将 MySQL 字段字符集从 latin1 更改为 utf8_general_ci 打破变音符号 (ä,ö,ü)
- angular - Karma-Jasmine:TypeError:无法读取未定义的属性(读取“get”)
- swift - 将 CVPixelBuffer 转换为 UIImage 的内存泄漏
- android-studio - Android模拟器发白显示问题
- xamarin.forms - 如何从后台安排在 Xamarin ios 中启动应用程序或任务?
- javascript - 一旦生成雷达图,它就会在图例和图表之间留下巨大的空间
- java - 使用没有值的 Java 8 Streams 遍历 java 中的列表
- python - 创建一个函数以在 python 中执行 T-Test
- highcharts - 以角度更改数据序列类型时出现 HighCharts 风刺的问题