Search code examples
c#sql-servertostringvisual-studio-2008-sp1executescalar

When i use ExecuteScalar command returns an empty object


What is wrong with my code?

When I use this block of code in Visual Studio 2008 C# the curid output value is "", where I have 2 values in my database so it should return 2...

Also when I run a query

select IDENT_CURRENT('tablename')

directly in SQL Server Management Studio, it returns the correct value.

string curid = "";

cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select IDENT_CURRENT('@tblname')";
cmd.Parameters.AddWithValue("@tblname", tableName);

cmd.Connection = con;
object obj = cmd.ExecuteScalar();
curid = obj.ToString();

Solution

  • Edit your CommandText to this:

    cmd.CommandText = "select IDENT_CURRENT(' " + tableName + "')";