I have a table of crop which contain a column with crop name For Example Fruit and Nuts, Vegetables and Melons. I have to use T-SQL and remove the 'and' insert the spaces with a underscore and a text crop.groups should be added in front. For example Fruit and Nuts will become crop.groups.fruit_nuts. I have to to do these for all the crops together in SQL. When we run the query a separate column with these transformation should be generated. Also I have to create a function doing all this to me.
My Function:
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
Sample data
Crop name : Beverages and spice crops
Translation output : crop.group.beverages_spice_crops