Friday, April 3, 2009

MS SQL tinyint, smallint, int, and bigint datatypes and equivalent in C#

First let's take a look at data range for int datatypes in MS SQL:


Datatype Range Storage
-------- ------_---------------------------- -------
bigint -2^63 (-9,223,372,036,854,775,808)
TO 8 bytes
2^63-1 (9,223,372,036,854,775,807)

int -2^31 (-2,147,483,648)
TO 4 bytes
2^31-1 (2,147,483,647)

smallint -2^15 (-32,768)
TO 2 bytes
2^15-1 (32,767)

tinyint 0 to 255 1 bytes


Then we have the following data conversion table too:


SQLServer Type SQL-92 Compliant Type C# Type CLS-Compliant Type
--------- -------------------------- ------- ------------------
bigint bigint long Int64
int integer int Int32
smallint smallint short Int16
tinyint tinyint byte Byte

Now we can find trhat if you have a column in tinyint datatype
and you want to get its value by a SqlDataReader, the method
which will work for you would be .GetByte( iClmnIndx )


public bool getMyTinyIntValue()
{
bool retVal = true;
int iTinyIntVal = 0;

using (SqlConnection sqlCn = new SqlConnection(sqlCnStr))
{
try
{
string strSqlCmd = "SELECT iTinyInt FROM myTable";

SqlCommand sqlCmd = new SqlCommand(strSqlCmd, sqlCn);
sqlCn.Open();

SqlDataReader sqlDtaRdr = sqlCmd.ExecuteReader();
if (sqlDtaRdr.Read())
iTinyIntVal = sqlDtaRdr.GetByte(0);
else retVal = false;

sqlDtaRdr.Close();
sqlCn.Close();
}
catch (Exception ex)
{
retVal = false;
MessageBox.Show(ex.ToString(),
"Error",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
finally
{
if (sqlCn != null) sqlCn.Close(); // Close the connection
}
return retVal;
}
}

Share/Bookmark

No comments: