0

Scenario: column contains numbers as ('1234', '123', '23456') - I need to replace the first number with 'A' and replace the remaining numbers with *.

Output should be:

A***
A**
A****

Can anyone help me? How to achieve this?

Thanks

5
  • 1
    If ('1234', '123', '23456') is literally the value in a single record/column, then it would be very difficult to do this with basic SQL Server. Why isn't your data normalized? Commented Aug 17, 2018 at 7:04
  • What have you tried so far? Is this homework? Commented Aug 17, 2018 at 7:04
  • '1234', '123', '23456' is this a single column value or 3 Rows in your table?? Commented Aug 17, 2018 at 7:07
  • I tried below. select concat('A',str1) as New_String from (select substr(colname,2,length(colname)) str1 from tablename); Commented Aug 17, 2018 at 7:13
  • its a 3 different rows in a table. Commented Aug 17, 2018 at 7:14

3 Answers 3

3

REPLICATE is best option for you.

CREATE TABLE #TAB(VAL VARCHAR(100))
INSERT INTO #TAB 
VALUES ('1234'), ('123'), ('23456')


SELECT 'A'+REPLICATE('*', LEN(VAL)-1)  FROM #TAB
Sign up to request clarification or add additional context in comments.

5 Comments

Same answer of me :)
be carefull to null value or value with len <= 1
Thanks for pointing. And I started writing answer on own. @Esperento57
your example dont bug with null value or len <=1, it give null as result. but is that what he wants as a result...
Thanks all I used the replicate and it works as expected. Thanks everyone
1

You can try this

Drop Table #MyTempTable

Create Table #MyTempTable (
    NAME NVARCHAR(100)
);

Insert Into #MyTempTable VALUES ('3243')
Insert Into #MyTempTable VALUES ('123')
Insert Into #MyTempTable VALUES ('432423')
Insert Into #MyTempTable VALUES ('423')
Insert Into #MyTempTable VALUES ('432')

select * from #MyTempTable

Update #MyTempTable 
SET NAME = 'A' + REPLICATE('*', len(NAME) - 1)

select * from #MyTempTable

You should use replicate command.

Replicate- Repeats a string value a specified number of times.

Before update command,

NAME
3243
123
432423
423
432

After Update command,

NAME
A***
A**
A*****
A**
A**

Comments

0

try this

drop TABLE #TestTable
CREATE TABLE #TestTable (val varchar(500));

INSERT INTO #TestTable (val)
VALUES ('123'), ('23456'), ('1234555');

select case when len(isnull(val, ''))<2 then 'A' else 'A' + REPLICATE('*', len(val) - 1) end 
from #TestTable

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.