1
 StrSqlLines = "Select * From dbo.SqlDtaToCreate WHERE DtaLineAccountToDebit = '" + Straccref + "' and DtaLineCode IN('" + joined + "')";

I am getting an error when i execute this query

Conversion failed when converting the varchar value '116743,116744,116745' to data type int.

However the query works fine from SQL

select * from SqlDtaToCreate where DtaLineAccountToDebit='123.567U' and DtaLineCode IN('116745','116746','116747')
vini
  • 4,657
  • 24
  • 82
  • 170

4 Answers4

2

First:

This might be a bad case of SQL injection! Use prepared statements (or at least proper escaping)!

Second:

Your immediate problem is the enclosing ' for the IN clause correctly:

 StrSqlLines = "Select * " +
               "From dbo.SqlDtaToCreate "
               " WHERE DtaLineAccountToDebit = '" + Straccref + "' " + 
               " and DtaLineCode IN(" + joined + ")"; //notice missing ' characters

Anything enclosed by ' characters is trated as a single string. SQL server tried to parse this single string as a number, but as it was not parseable as that, it reported the error.

Third:

When using numeric data, never ever ever, never, ever (did I mention never yet?) use textual data to compare it with - that can literally kill performance. (at this scale, of course this is not significant, but keeping this in mind can save a lot of unnecessary performance analysis and debugging...)

So while this query actually works:

select * from SqlDtaToCreate where DtaLineAccountToDebit='123.567U' and DtaLineCode IN('116745','116746','116747')

It does implicit conversion of the data supplied, so the proper way is to:

select * from SqlDtaToCreate where DtaLineAccountToDebit='123.567U' and DtaLineCode IN(116745,116746,116747)
ppeterka
  • 20,583
  • 6
  • 63
  • 78
0

Notice missing ' in your joined variable.

'116743,116744,116745'

'116745','116746','116747'

Ideally, since you're comparing INTs all you need is

116743,116744,116745

And read about sql injection.

Jakub Konecki
  • 45,581
  • 7
  • 87
  • 126
0

Its the conversion on the term joined, it seems the Database server can convert a number contained in quotes but not more than on esparated by comma, in your case:

'116743,116744,116745'

To :

'116745','116746','116747'

Try to reformat joined to separate the numbers by quotes., or remove the quotes from the sql statament so you get IN(" + joined + ")" instead of: IN('" + joined + "')"

CloudyMarble
  • 36,908
  • 70
  • 97
  • 130
0

Note that your two queries are not the same. The programmatic one puts single quotes around the entire group of numbers, while your SQL test puts single quotes around each number.

Probably you can just omit quotes altogether, though:

StrSqlLines = "Select * From dbo.SqlDtaToCreate WHERE DtaLineAccountToDebit = '" 
   + Straccref + "' and DtaLineCode IN(" + joined + ")";