2

I have an SQL select statement:

select pk from items

it returns:

1
2
4
29
8
987654
12313232

Now my boss wants something like:

000001
000002
000004
000029
000008
987654
12313232

He definitely want the output to be six digits minimum (which I think nonsense).

I've tried doing something like '00000' + convert(nvarchar(6),pk) which works okay only if the pk is just one digit. Do you have any idea how to do this? Should I use conditional statement?

kazinix
  • 28,987
  • 33
  • 107
  • 157

1 Answers1

5

Normally this

RIGHT ('000000' + CONVERT(varchar(6), pk), 6)

But as you have values more than 6 digits, try this

LTRIM(RIGHT ('    000000' + CONVERT(varchar(10), pk), 10))

But you need a CASE to deal with numbers that are 7-9 digits long:.

CASE
    WHEN pk >= 1000000 THEN CONVERT(varchar(10), pk)
    ELSE RIGHT ('000000' + CONVERT(varchar(6), pk), 6)
END
gbn
  • 422,506
  • 82
  • 585
  • 676
  • How if it's more than 6 digits? Also, cast doesn't work in my query, I'm using 2008. – kazinix Aug 01 '11 at 08:04
  • I think I really need a conditional statements. Either your first and second answer doesn't work right. Thanks anyway. – kazinix Aug 01 '11 at 08:21