我正在尝试执行动态sql选择,我在使用参数从表中选择。
SELECT null FROM @TableName
但是我收到错误must declare table variable @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执行上述操作? (请不要存储程序)
答案 0 :(得分:5)
您不能将参数用于表格和列名称。对于那些您可能具有可能值的白名单,然后在构建SQL查询时使用字符串连接。
答案 1 :(得分:4)
您不能使用这样的参数,因此您必须将查询构建为字符串。您可以在SQL中执行此操作,但您也可以在C#代码中创建字符串。
确保表名和字段名是安全且值得信赖的值,并且不会直接来自Web请求等不安全的来源。
string tableName = "testtable";
string fieldName = "testfield";
List<SqlParameter> sqlParams = new List<SqlParameter>() {
new SqlParameter("Find", "testfind"),
};
string sqlSelect =
"SELECT null " +
"FROM " + tableName + " " +
"WHERE " + fieldName + " LIKE '%' + @Find + '%' ";
答案 2 :(得分:1)
private DataTable ExecuteDynamic(string TableName,string FieldName, string Find)
{
string sqlSelect = "SELECT * FROM " + TableName +
" WHERE " + FieldName + " LIKE '%'" + Find + "'%' ";
using (connection = new SqlConnection(Strcon))
connection.Open();
{
using (cmd = new SqlCommand(sqlSelect, connection))
{
cmd.CommandType = CommandType.Text;
cmd.CommandTimeout = 60;
adpt = new SqlDataAdapter(cmd);
dt = new DataTable();
adpt.Fill(dt);
return (dt);
}
}
}