如果表具有相同的列,我会选择类似的东西。使用 sql UNION
。
var statesTables = new[]{"NY, Texas, Oregano, Alabama}";
var qBuild = new StringBuilder();
qBuild.Append(string.Format("SELECT * FROM {0} WHERE UserId = @userId ", statesTables[0]));
for(int i=1;i<stateTables.Length;i++){
qbuild.Append(string.Format("UNION SELECT * FROM {0} WHERE UserId = @userId ", statesTables[i]))
}
SqlConnection conn1 = new SqlConnection(connString);
SqlCommand comm1 = new SqlCommand(qBuild.ToString(), conn1);
comm1.Parameters.Add(new SqlParameter("userId", userId));
它将生成 SQL:
SELECT * FROM NY WHERE UserId = @userId
UNION
SELECT * FROM Texas WHERE UserId = @userId
UNION
SELECT * FROM Oregano WHERE UserId = @userId
UNION
SELECT * FROM Alabama WHERE UserId = @userId
如果有一些不同的列,请将 * 替换为表共有的列名。
但是,正如其他人所建议的那样,重构您的数据库模式将是最好的!