【问题标题】:How can i select from table where tablename is specified as SqlParameter?如何从表名指定为 SqlParameter 的表中进行选择?
【发布时间】:2011-11-25 18:54:50
【问题描述】:

我正在尝试在使用参数从表中选择的位置执行动态 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 执行上述操作? (请不要存储过程)

【问题讨论】:

    标签: c# dynamic-sql sqlhelper


    【解决方案1】:

    您不能将参数用于表名和列名等内容。对于那些你可以有一个可能值的白名单,然后在构建 SQL 查询时使用字符串连接。

    【讨论】:

      【解决方案2】:

      您不能使用这样的参数,因此您必须将查询构建为字符串。您可以在 SQL 中执行此操作,但也可以只在 C# 代码中创建字符串。

      确保表名和字段名是安全且受信任的值,而不是直接来自网络请求等不安全来源。

      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 + '%' ";
      

      【讨论】:

        【解决方案3】:
            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);
                }
            }
        }
        

        【讨论】:

        • 您忘记在代码中使用TableName 参数...而TableNameWHERE 将无法运行...
        猜你喜欢
        • 1970-01-01
        • 2012-05-15
        • 1970-01-01
        • 2015-05-06
        • 2014-01-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多