0

How to fix this issue in my code:

str = "SELECT " + columnName + " FROM [tableA] where Company_ID=" + HaksId.ToString() + "";
cmd.CommandText = str;
cmd.Connection = conn;
adpt.SelectCommand = cmd;
adpt.Fill(ds);

In the above code there is only required things mentioned obviously conn is connection string I have mentioned all things they are working fine there is some other error in this code

Where columnname is string and Id is integer

Error is

Conversion failed when converting the nvarchar value '[Select]' to data type int.

Return value is value of type decimal(18,0)

Hoping for your suggestion

Thanks

EDITED

columname="Avg"
HaksId=1

Company_ID is of nvarchar

Result of query should be 2.

SOLUTION

This help me out,

"SELECT " + columnName + " FROM [tableA] where Company_ID='" + HaksId+ "'"
6
  • We can't see the values of columnName or HaksId; so: what is the resulting value of str here? Also: Does ds.Tables[0] have columns defined? If so: as what? Commented Aug 20, 2014 at 9:51
  • Whate is the data type for Company_ID in table Commented Aug 20, 2014 at 9:54
  • Company_ID = int isn't it? if it's, then u're comparing it with string. Commented Aug 20, 2014 at 9:55
  • I would suggest using a parameter for the ID. It might also help with the confusion of types. Commented Aug 20, 2014 at 9:57
  • i have mentioned all things above kindly check it Commented Aug 20, 2014 at 9:57

1 Answer 1

2

Parameters should solve the problem here. I would change this;

str = "SELECT " + columnName + " FROM [tableA] where Company_ID=" + HaksId.ToString() + "";

To this;

str = "SELECT " + columnName + " FROM [tableA] where Company_ID = @CompanyID";

Then use this;

adpt.SelectCommand.Parameters.Add("@CompanyID", SqlDbType.Int).Value = Haks;
adpt.Fill(ds);
Sign up to request clarification or add additional context in comments.

4 Comments

columnID does not exsis in the current context
See Can we stop using AddWithValue already? - I would recommend to use a "normal" Parameters.Add(....).Value = .... approach.
@FizzBuzz: read the article I linked to! It explains in great detail why AddWithValue is dangerous
@marc_s Err, didn't realise it was a link, my bad. Nice article and duly noted.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.