如何动态查询多个表VB.NET

时间:2015-01-22 13:45:59

标签: vb.net

我的数据库中有30个不同的表,每个表在每个表中都有相同的列名"res_ret"=define as 0。我想更新并设置res_ret value=1。这是我的代码,这是工作。我怎么能在动态编码中做到这一点。在此先感谢:)

conn.Open()

sql = "Update table_1 SET res_ret= 1"
cmd.CommandText = sql
cmd.Connection = conn
cmd.ExecuteNonQuery()

sql = "Update table_2 SET res_ret=1"
cmd.CommandText = sql
cmd.Connection = conn
cmd.ExecuteNonQuery()

sql = "Update table_3 SET res_ret=1"
cmd.CommandText = sql
cmd.Connection = conn
cmd.ExecuteNonQuery()

conn.Dispose()
conn.Close()

2 个答案:

答案 0 :(得分:1)

正如@TimSchmelter指出的那样,可能有更好的方法,但是:

VB.NET

Dim tableList = { "table_1", "table_2", "table_3" }

For Each tableName As String In tableList
    cmd.CommandText = String.Format("update {0} set res_ret = 1", tableName)
    cmd.ExecuteNonQuery()
Next

C#

var tableList = new List<string> { "table_1", "table_2", "table_3" ... };

foreach(var tableName in tableList) {
    cmd.CommandText = string.Format("update {0} set res_ret = 1", tableName);
    cmd.ExecuteNonQuery();
}

答案 1 :(得分:0)

最后这段代码工作.. Dim tableList = {“table_1”,“table_2”,“table_3”}

        For Each tableName As String In tableList
            conn.Open()
            cmd.CommandText = String.Format("update {0} set res_ret = 1", tableName)
            cmd.Connection = conn
            cmd.ExecuteNonQuery()
            conn.Dispose()
            conn.Close()
        Next