2

I have a table DomainDetail having a column fieldID.

It has values like A1,B22,A567,D7779,B86759 .. i.e. from two characters to max six characters.

I want these values have equal number of characters A000001,B000022,A000567,D07779 and B86759 .

This is how I think I should proceed

  • Estimate size of field value = LEN(fieldID)
  • Insert number of zeros equal to (6 - number of characters) .

How can I insert 0's sandwiched inside original value . How can do in SQL ?

Mudassir Hasan
  • 28,083
  • 20
  • 99
  • 133

5 Answers5

4

like this

select 
    left(fieldID, 1) + 
    right('000000' + right(fieldID, len(fieldID) - 1), 5)
from DomainDetail

take a look at SQL FIDDLE example

Roman Pekar
  • 107,110
  • 28
  • 195
  • 197
2

It sounds like a problem better solved by business logic, i.e. the layer of code above your database. Whenever you insert, do the padding in that code - then always use that code/layer to insert into the table.

It seems to be a business logic requirement anyway - "ID must have a maximum 6 characters". Because a database wouldn't impose such a limit.

(unless you are using stored procedures as your business logic layer? in which case, PadLeft function in T-SQL)

Community
  • 1
  • 1
Kieren Johnstone
  • 41,277
  • 16
  • 94
  • 144
1
select 
stuff(fieldId,2,0,
      LEFT('0000000000000000000000000',
      (select max(LEN(FieldID)) from DomainDetail)

           -LEN(fieldId)))
from DomainDetail

If you need a fixed output length just replace inner select (select max(LEN(FieldID)) from DomainDetail) with for example 6 Here is a SQLFiddle demo

valex
  • 23,966
  • 7
  • 43
  • 60
1

If you want to UPDATE, then use this

UPDATE DomainDetail
SET fieldId=
            SUBSTRING(fieldId,1,1)+
            REPLICATE('0',6-LEN(id))+
            SUBSTRING(fieldId,2,LEN(id)-1)

If you want to just SELECT without altering the values in the table, then this should work

SELECT SUBSTRING(id,1,1)+
       REPLICATE('0',6-LEN(id))+
       SUBSTRING(id,2,LEN(id)-1) 
FROM DomainDetail

Hope this helps,

Raj

Raj
  • 10,653
  • 2
  • 45
  • 52
1
select stuff(fieldid, 2, 0, replicate('0', 6-len(fieldid))) 
from DomainDetail
t-clausen.dk
  • 43,517
  • 12
  • 59
  • 92