如何从表名指定为 SqlParameter 的表中进行选择?
我正在尝试执行动态 sql 选择,我使用参数从表中进行选择。
SELECT null FROM @TableName
但是我收到错误必须声明表变量@TableName
。我怀疑这是因为我正在使用变量从表中进行选择。我以前不需要这样做。
List<SqlParameter> sqlParams = new List<SqlParameter>()
{
new SqlParameter("TableName", "testtable"),
new SqlParameter("FieldName", "testfield"),
new SqlParameter("Find", "testfind"),
};
string sqlSelect = "SELECT null FROM @TableName
WHERE @FieldName LIKE '%' + @Find + '%' ";
DataTable dtSelect = SqlHelper.ExecuteDataset(sqlConn, CommandType.Text,
sqlSelect, 30, sqlParams.ToArray()).Tables[0];
//30 = timeout
如何使用动态 sql 执行上述操作? (请不要存储过程)
I am trying to perform dynamic sql select where I am selecting from a table using a parameter.
SELECT null FROM @TableName
However I am getting error must declare table variable @TableName
. I suspect this is because I am selecting from a table using a variable. I have not needed to do this before.
List<SqlParameter> sqlParams = new List<SqlParameter>()
{
new SqlParameter("TableName", "testtable"),
new SqlParameter("FieldName", "testfield"),
new SqlParameter("Find", "testfind"),
};
string sqlSelect = "SELECT null FROM @TableName
WHERE @FieldName LIKE '%' + @Find + '%' ";
DataTable dtSelect = SqlHelper.ExecuteDataset(sqlConn, CommandType.Text,
sqlSelect, 30, sqlParams.ToArray()).Tables[0];
//30 = timeout
How can I perform the above using dynamic sql? (no stored procedures please)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您不能对表名和列名等参数使用参数。对于那些您可以有一个可能值的白名单,然后在构建 SQL 查询时使用字符串连接。
You cannot use parameters for things like table and column names. For those you could have a whitelist of possible values and then use string concatenation when building the SQL query.
您不能使用这样的参数,因此您必须将查询构建为字符串。您可以在 SQL 中执行此操作,但也可以仅在 C# 代码中创建字符串。
确保表名称和字段名称是安全且可信的值,并且不是直接来自不安全的来源(例如 Web 请求)。
You can't use parameters like that, so you have to build the query as a string. You could do that in SQL, but you can also just create the string in the C# code.
Make sure that the table name and field name are safe and trusted values, and doesn't come directly from an unsafe source like a web request.