开发者

Hypen "-" is not getting accepted in SQL Parameter

I have this piece of code

string strSQLQuery = "SELECT " + strF开发者_StackOverflow社区ieldName + " FROM " + strTableName +
" WHERE " + strFieldName + " = @Value";

sqlCmd.CommandText = strSQLQuery;
sqlCmd.Connection = con;
sqlCmd.Parameters.AddWithValue("@Value", strFieldValue);
resultValue = sqlCmd.ExecuteScalar();

My strFieldValue is "IGEM - Italy"

Where as if I execute it directly without Parameter it executes

string strSQLQuery = "SELECT " + strFieldName + " FROM " + strTableName +
" WHERE " + strFieldName + " = '" + strFieldName  + "'";

Please advise


What's the purpose of this code?

You appear to build your query, but you don't handle special chars in your field name, you should delimit it:

string strSQLQuery = 
    "SELECT [" + strFieldName + "] " +
    "FROM [" + strTableName + "] " +
    "WHERE [" + strFieldName + "] = @Value";

That query will work even when strFieldName = "IGEM-Italy", whereas your first query will fail if the field name has the hyphen.

However this statement will always return the same thing, as you're returning the field that you're filtering by.

Your second query has:

" WHERE " + strFieldName + " = '" + strFieldName  + "'"

Which isn't the same thing - I figure it's a typo.


Maybe you should enclose the strFieldValue with single quotes. Furthermore, is the strFieldValue of datatype string?


I am not experienced on .Net.

  • .AddWithValue("Value", ...) without @ maybe? - SORRY SEEMS TO BE WITH @.
  • Type conversion NVARCHARS?
  • Xxx instead of Value? Value being an SQL key word or so.


I figured it out actually in SQL database it is '-' hypen but the code which i am sending was EM Dash "-"

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜