SQLTeam.com | Weblogs | Forums

How to convert characters or number to underscore and after that concatenate it

I work on sql server 2012 i face issue I need to convert characters and numbers to underscore " "
and after that concatenate it based on length of number or charachters
so if one character or one number will be

so if two character or two number will be
so if three character or three number will be _
so How to make select query do above on test sample below

 create table portionstable
 PortionKey nvarchar(20)
 insert into portionstable(PortionKey)
 select * from portionstable

what i try but not working

select concat(replace(PortionKey,PortionKey,'_' )) as portionkeyfrom portionstable
so how to do it


one idea is to do multiple replaces for all numbers and alphabets ( you can put this inside a function )
select replace 1 replace 2 replace 3


please see if regular expressions can be used


you can use C# or some other language other than T-SQL to do it

Hope this helps :slight_smile:

No need for REPLACE at all:

SELECT REPLICATE(N'_',LEN(PortionKey)) FROM PortionsTable
1 Like

Nice Idea Robert Volk :+1: :+1:

if all the characters are numbers or letters

That's the same answer I provided over at SQLServerCentral.

Brilliant minds think alike :wink:

Heh... thank you but we may not be so brilliant if the requirement is to not replace spaces (and other non-alphanumeric characters) in a multi-word string. :smiley: That would require a slightly different set of hammers (DelimitedSplit8K and STRING_AGG, if the later is available). :smiley:

TRANSLATE() might be an option too, and would be the best solution.

Although I've not had to use TRANSLATE in the past, I can definitely see it fitting in there quite nicely. I wonder what the performance of the function would actually be?

Heh... but first, I wish @ahmedbarbary would tell us why this needs to be done to begin with! :smiley: