Вопрос

I have a field in my SQL Server 2012 table defined as Int. but when I try to get the value from a textbox in C# using the converting (Convert.toint32(textbox.text)). Lets say if the textbox contains the number 0032, it will be saved to the database as 32 removing the 00.

Any solutions other than changing the Field Data Type??

Это было полезно?

Решение

Numeric datatypes do not retain leading zeros, as they are insignificant to the number you want to store. Char or Varchar is more appropriate. You could set a constraint to ensure only numeric characters are stored.

If you absolutely cannot change the data type, then another alternative is to store the number of leading zeros into another int field

So in your example you would store:
Value : 32
Leading zeros : 2

Другие советы

So save to the db in a numeric format - ignoring the leading zero's (as the others have mentioned) and then format like this example:

int i  = 32;
string format = "0000";
Console.WriteLine(i.ToString(format));

A datatype is defined by set of possible values and operations that can be done on them.

So, the question here is: what operations will you do on that values? Summing, adding, multiplying...?

If answer is 'no', then change the column's type to varchar() or char() and store the value as-is, with the leading zeroes.

If it's 'yes', then store a proper number and leave the formatting to the client.

In any case, always try to use a proper datatype in the database, domain integrity is a nice thing to have.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top