0

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();
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
anotherday
  • 23
  • 3
  • 2
    As far as I know, you *cannot* parametrize the table name here - you'd have to use simple string concatenation to build that query you successfully execute in SSMS and then run that against SQL Server. – marc_s Mar 21 '15 at 13:14
  • 3
    additionally, one would *not* place a parameter within single-quotes. – Sam Axe Mar 21 '15 at 13:16
  • sorry i didnt know that,, i was used to parameterized query anyways i've already solved this – anotherday Mar 21 '15 at 13:47
  • I was wrong in my first comment - you *can* indeed use a parameter here - as long as you don't put it into single quotes (and preferably don't use the `.AddWithValue` method - [see here for more details *why* to avoid that](http://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/) ). – marc_s Mar 21 '15 at 14:22

1 Answers1

-1

Edit your CommandText to this:

cmd.CommandText = "select IDENT_CURRENT(' " + tableName + "')";
Posiedon
  • 134
  • 1
  • 8