How to Convert Sqldecimal to Int32 in C#

Platform: Windows Mobile, SqlCE2.0

Problem:
You want to get the id of the last query you insert.

Solution:
Using the @@identity you have to execute your queries like this:


SqlCeConnection conn = null;
try {
conn = new SqlCeConnection(GetConnection());
conn.Open();

//execute the insert statement
SqlCeCommand cmd = conn.CreateCommand();
cmd.CommandText = sql;
cmd.ExecuteNonQuery();

//get the last insert id
cmd.CommandText = "SELECT @@IDENTITY"; //using identity
//take note ExecuteScalar return an object, and in sqlce @@identity returns SqlDecimal
SqlDecimal x = (SqlDecimal)cmd.ExecuteScalar();
//so my way of converting it to int is catch the value as SqlDecimal
//convert that to string and then convert the string to int
//this way works for me
id = Convert.ToInt16(x.ToString());
}


Note:
1.) @@IDENTITY returns SqlDecimal so you need to convert it to integer

1 Comments

  1. Thank you! In my case it was sufficient to pipe the return value from cmd.ExecuteScalar() directly into Convert.ToInt32()

    ReplyDelete

Post a Comment

Post a Comment

Previous Post Next Post
NERV Open Source
Building production Spring Boot systems?

Explore NERV — open-source Java libraries for audit trails, persistence, exception handling, and reliable event-driven architecture.