Reverse strings in SQL Server -
i have table product values below:
apple iphone
iphone apple
samsung phone
phone samsung
i want delete products table exact reverse(as consider them duplicates), such instead of 4 records, table have 2 records
apple iphone
samsung phone
i understand there reverse function in sql server, reverse whole string, , not i'm looking for.
i'd appreciate suggestions/ideas.
assuming dictionary not include xml entities (e.g. >
or <
), , not practical manually create bunch of update
statements every combination of words in table (if practical, simplify life, stop reading answer, , use justin's answer), can create function this:
create function dbo.splitsafestrings ( @list nvarchar(max), @delimiter nvarchar(255) ) returns table schemabinding return ( select item = ltrim(rtrim(y.i.value('(./text())[1]', 'nvarchar(4000)'))) ( select x = convert(xml, '<i>' + replace(@list, @delimiter, '</i><i>') + '</i>').query('.') ) cross apply x.nodes('i') y(i)); go
(if xml problem, there other, more complex alternatives, such clr.)
then can this:
declare @x table(id int identity(1,1), s varchar(64)); insert @x(s) values ('apple iphone'), ('iphone apple'), ('iphone samsung hoochie blat'), ('samsung hoochie blat iphone'); ;with cte1 ( select id, item @x x cross apply dbo.splitsafestrings(lower(x.s), ' ') y ), cte2(id,words) ( select distinct id, stuff((select ',' + orig.item cte1 orig orig.id = cte1.id order orig.item xml path(''), type).value('.[1]','nvarchar(max)'),1,1,'') cte1 ), cte3 ( select id, words, rn = row_number() on (partition words order id) cte2 ) select id, words, rn cte3 -- rn = 1 -- rows keep -- rn > 1 -- rows delete ;
so could, after 3 ctes, instead of final select
above, say:
delete t @x t inner join cte3 on cte3.id = t.id cte3.rn > 1;
and should left in @x
?
select id, s @x;
results:
id s -- --------------------------- 1 apple iphone 3 iphone samsung hoochie blat
Comments
Post a Comment