Storing an int to SQL, but keep leading zeros

人盡茶涼 提交于 2020-01-04 06:50:32

问题


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??


回答1:


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




回答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));



回答3:


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.



来源:https://stackoverflow.com/questions/23309114/storing-an-int-to-sql-but-keep-leading-zeros

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!