2

Here is my code but it returns -1 value. The Name field contains a unicode value.

  using (SqlConnection conn = new SqlConnection(connStr))
  {      
      string str = string.Format("select SrNo from Jat where Name=@Name");
      SqlCommand dCmd = new SqlCommand(str, conn);
      try
      {               
          dCmd.Parameters.AddWithValue("@Name","N" +Name);
          int i= dCmd.ExecuteNonQuery();
          return i;
      }
      catch
      { 
           throw; 
      }
   }
Leigh
  • 28,765
  • 10
  • 55
  • 103
Somnath
  • 249
  • 3
  • 12

2 Answers2

2

there is no need to write down

dCmd.Parameters.AddWithValue("@Name","N" +Name); 

remove "N" from this but it doesnt create nvarchar parameter

dCmd.Parameters.AddWithValue("@Name", Name); 

To create nvarchar type parameter than you can do this

dCmd.Parameters.Add(new SqlParameter("@Name", SqlDbType.NVarChar)).Value = Name; 

this will create nvarchar parameter than you can add this parameter as nvarchar parameter

one more change in code is make use of ExecuteScalar

int i= Convert.ToInt32( dCmd.ExecuteScalar());

make use of ExecuteScalar method rather than ExecuteNonQuey ....becuase non Sclar method return value of you SrNo and NonQuery return you row affected when using update and insert query

Pranay Rana
  • 175,020
  • 35
  • 237
  • 263
  • @Somnath - Check your database against the passed in name. The query requires it to be _identical_. – Oded Sep 20 '12 at 09:01
  • @Somnath - make use of ExecuteScalar method rather than ExecuteNonQuey ....becuase non Sclar method return value of you SrNo and NonQuery return you row affected when using update and insert query – Pranay Rana Sep 20 '12 at 09:03
  • thanks @PranayRana it works by using int i= Convert.ToInt32( dCmd.ExecuteScalar()); – Somnath Sep 20 '12 at 09:05
1

First, the N'' is only required in TSQL for Unicode string literals.

Second, if you want to return the SELECTed SrNr, use ExecuteScalar()

devio
  • 36,858
  • 7
  • 80
  • 143