views:

308

answers:

2

I am trying to insert a record and get its newly generated id by executing two queries one by one, but don't know why its giving me the following error.

Object cannot be cast from DBNull to other types

My code is as below: (I don't want to use sql stored procedures)

SqlParameter sqlParam;
    int lastInsertedVideoId = 0;

    using (SqlConnection Conn = new SqlConnection(ObjUtils._ConnString))
    {
        Conn.Open();
        using (SqlCommand sqlCmd = Conn.CreateCommand())
        {
            string sqlInsertValues = "@Name,@Slug";
            string sqlColumnNames = "[Name],[Slug]";
            string sqlQuery = "INSERT INTO videos(" + sqlColumnNames + ") VALUES(" + sqlInsertValues + ");";
            sqlCmd.CommandText = sqlQuery;
            sqlCmd.CommandType = CommandType.Text;

            sqlParam = sqlCmd.Parameters.Add("@Name", SqlDbType.VarChar);
            sqlParam.Value = txtName.Text.Trim();

            sqlParam = sqlCmd.Parameters.Add("@Slug", SqlDbType.VarChar);
            sqlParam.Value = txtSlug.Text.Trim();


            sqlCmd.ExecuteNonQuery();

            //getting last inserted video id
            sqlCmd.CommandText = "SELECT SCOPE_IDENTITY() AS [lastInsertedVideoId]";
            using (SqlDataReader sqlDr = sqlCmd.ExecuteReader())
            {
                sqlDr.Read();
                lastInsertedVideoId = Convert.ToInt32(sqlDr["lastInsertedVideoId"]);
            }
        }
    }

    //tags insertion into tag table
    if (txtTags.Text.Trim().Length > 0 && lastInsertedVideoId > 0)
    {
        string sqlBulkTagInsert = "";
        string[] tags = txtTags.Text.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
        foreach (string tag in tags)
        {
            sqlBulkTagInsert += "INSERT INTO tags(VideoId, Tag) VALUES(" + lastInsertedVideoId + ", " + tag.Trim().ToLowerInvariant()+ "); ";
        }

        using (SqlConnection Conn = new SqlConnection(ObjUtils._ConnString))
        {
            Conn.Open();
            using (SqlCommand sqlCmd = Conn.CreateCommand())
            {
                string sqlQuery = sqlBulkTagInsert;
                sqlCmd.CommandText = sqlQuery;
                sqlCmd.CommandType = CommandType.Text;

                sqlCmd.ExecuteNonQuery();
            }
        }
    }

And also if possible, please check is the above code coded well or we can optimize it more for improve performance?

Thanks

A: 

The SCOPE_IDENTITY() should be extracted from the first command (SELECT, RETURN or OUT) and passed into the next command. By that, I mean that the SELECT_IDENTITY() should be at the end of the first command. In SQL 2008 there is additional syntax for bring values back as part of the INSERT, which makes this simpler.

Or more efficiently: combine the commands into one to avoid round-trips.

Marc Gravell
but using `sqlCmd.ExecuteNonQuery();` how will we get the identity value in a variable? and one more thing I don't want to use sql stored procedures.
Prashant
Or it will be nice if you can provide any sample code, thanks.
Prashant
If it is an `OUT` param, then `ExecuteNonQuery` is fine - ditto if it is a `RETURN` parameter; if it is a `SELECT`, then use `ExecuteReader` or `ExecuteScalar`. Note that an `OUT`/`RETURN` is *marginally* more efficient than `SELECT`, but not by a huge amount.
Marc Gravell
+4  A: 

The call to SCOPE_IDENTITY() is not being treated as being in the same "scope" as the INSERT command that you're executing.

Essentially, what you need to do is change the line:

string sqlQuery = "INSERT INTO videos(" + sqlColumnNames + ") VALUES(" + sqlInsertValues + ");";

to:

string sqlQuery = "INSERT INTO videos(" + sqlColumnNames + ") VALUES(" + sqlInsertValues + "); SELECT SCOPE_IDENTITY() AS [lastInsertedVideoId]";

and then call

int lastVideoInsertedId = Convert.ToInt32(sqlCmd.ExecuteScalar());

instead of .ExecuteNonQuery and the code block following the "//getting last inserted video id" comment.

Rob
Looks good, let me try this out.
Prashant
I don't know why but its giving me `System.InvalidCastException: Specified cast is not valid.` error when I am doing it like `int lastVideoInsertedId = (int)sqlCmd.ExecuteScalar();`
Prashant
Got it: I tried it like `int lastVideoInsertedId = Convert.ToInt32(sqlCmd.ExecuteScalar());` and its working. I don't know the reason, if you know please explain. And also please edit your answer and include this conversion method. Thanks
Prashant
Having just written up a quick test program, it appears that (at least from my contrived example running against Sql Server 2008) the underlying datatype was System.Decimal, rather than the Int32 that I expected, how very bizarre!
Rob