首页 > 解决方案 > 与字符串操作有关

问题描述

我有一个作物表,其中包含一个作物名称列,例如水果和坚果、蔬菜和瓜类。我必须使用 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

标签: sqlsql-servertsql

解决方案


这看起来很简单,使用replace

select cropname, Concat('crop.groups.', Replace(cropname, ' and ','_'))
from crop

推荐阅读