-1

SQL Query For Create Table

CREATE TABLE Test
(ID int,
 Value1 int,
 Value2 int,
)

SQL Query For Insert Value

  INSERT INTO Test
  VALUES(001,200,300)

OutPut

ID    Value1    Value2
1     200       300

Query To Display 00 In Result

SELECT RIGHT('00' + CAST([ID] AS varchar(5)) , 3),Value1,Value2
FROM Test

Now The Output Is

001 200   300

My Id Value Is maximum 5 Digit

Example 00001,00010,00100,01000,10000

Now i Want To Display The Result Like

   00001,00010,00100,01000,10000

I Need A Query Automatically Find Out How Many Zero Present Before The Number

Example 00001 This Value Have 4zero , 00010 This Value Have 3 Zero.

How To Use This Query

 SELECT RIGHT('00' + CAST([ID] AS varchar(5)) , 3),Value1,Value2
 FROM Test

For Find Out How Many Zero Present And Display The Result With zero

Gurunathan
  • 467
  • 1
  • 5
  • 19

5 Answers5

7

Numeric data types don't contain leading zeros. If you need to store leading zeros, you need to use a character datatype.

If you do that, however, to store numbers without leading zeros, please note that sorting on a character datatype field is done lexicographically, so you might end up with something like this:

1
10
11
2
20
21

Also, you should note the difference between data storage and data display. You could well store numbers without leading zeros, but make your application display them containing leading zeros!


As other people have noted, something like

SELECT RIGHT('00' + CONVERT(NVARCHAR, Field), 3)

will help you select the content of a numeric field as a string with leading zeros.

You could also do that in C# using

String.Format("{0:d3}", fieldvalue);
Thorsten Dittmar
  • 55,956
  • 8
  • 91
  • 139
3

You are basically saying "I want to store a non-integer value in an integer column, how do I do that?"

Now, the obvious answer is of course: you don't.

The real question is, why do you think you want this? If (as I suspect) it is for later display purposes, then forget about inserting invalid data and focus on the real issue: how do I display my data the way I want to?

And the answer to that is simply": anywhere but in your database :)

You can change your integer to a string before displaying, either in your select statement, or further on in your front end.

oerkelens
  • 5,053
  • 1
  • 22
  • 29
1

You'd have to format the number manually. One way to do that:

select  right('00' + cast(ID as varchar(3)),3)
Andomar
  • 232,371
  • 49
  • 380
  • 404
1
SELECT RIGHT('00' + CAST([ID] AS varchar(5)) , 3)
FROM test

The 3 is the number of characters you want total in the output display

Nagaraj S
  • 13,316
  • 6
  • 32
  • 53
0

First you can't insert the value 00002 or anything like that with zeros (only in int type)... so the concept is fully wrong... or else change your data type to varchar then you can do these things...

if you are using varchar then simply use the following function

reverse()
Liam
  • 27,717
  • 28
  • 128
  • 190
vino20
  • 429
  • 4
  • 13