How to pass a column name value as SQL argument using placeholders

喜欢而已 提交于 2019-12-01 22:54:20

The short answer is that you can't; parameters are only supported for values, not for column names.

You either have to fall back on direct text insertion as Richard has said (whether this happens in code or via the use of the SQL Server exec() function), or use some kind of a library (like LINQ) that lets you construct queries dynamically and then converts that into a text representation.

If you go the direct text insertion route, be very sure that you are not allowing direct user input to be inserted; do some kind of translation yourself to avoid SQL Injection attacks.

I'm looking at what you've tried, and you've just left out the obvious one:

var sql = "SELECT * FROM Condos WHERE " + choice + " LIKE @1";
var sqlData = db.Query(sql,choice,"%"+searchString+"%");

The only reason you will need to escape the column name is when it is a reserved word, such as Order. In that case, you will need to use the database-specific identifier escape character.

For example, MySQL:

var sql = "SELECT * FROM Condos WHERE `" + choice + "` LIKE @1";
var sqlData = db.Query(sql,choice,"%"+searchString+"%");

SQL Server

var sql = "SELECT * FROM Condos WHERE [" + choice + "] LIKE @1";
var sqlData = db.Query(sql,choice,"%"+searchString+"%");
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!