我有两个具有相同名称/模式但具有不同值的表。
我需要找到具有相同主键(第一列)但值不同的行。
例如
我的表:

id   name   age
1    ram    25
2    mohan   30


我的表:

id  name  age
3   harry  26
**1   ram   35**
3   tony   45


所以我需要2表中的2行,其值为35。
它应返回整行作为数据表或数据行。
我正在使用oracle数据库。此解决方案需要的C#代码。
并且它也应适用于其他表的多个列值。
我的代码..

public OracleCommand getColumns(OracleConnection connection, DataTable table, int i, string tab, DataTable table3)
{
    int columCount = table.Columns.Count;
    string [] colArray = new string[columCount];
    string pkey = table.Columns[0].ColumnName;
    string pkeyValue = table.Rows[i][0].ToString();
    string query2 = "SELECT * FROM " + tab +
                " WHERE " + tab + "." + pkey + " = '" + pkeyValue + "'";
    OracleCommand command = new OracleCommand();
    int k = 0;
    int  X =0;

    for(int j=1 ; j<colArray.Length;j++)
    {
        string column = table.Columns[j].ColumnName;
        string columnValue = table.Rows[i][j].ToString();
        string add = " OR " + tab + "." + column + " = '" + columnValue + "'";
        query2 += add;
        command.CommandText = query2;
        command.CommandType = CommandType.Text;
        command.Connection = connection;
        var check = command.ExecuteNonQuery();
        if (check == null)
        {
            k++;
        }
        else
            X++;
    }
     return command;
}

最佳答案

这是您的表的示例,我正在显示来自t2的数据,这些数据与t1中的行不匹配:

using Oracle.DataAccess.Client;

...

public string OraText(string pkey, string[] tables, string[] columns)
{
    string sSQL = "select " + pkey + "";
    foreach (string s in columns)
    {
        sSQL += ", " + tables[1] + "." + s;
    }
    sSQL += Environment.NewLine + "  from t1 join t2 using (" + pkey + ") "
        + Environment.NewLine + "  where 1=0 ";
    foreach (string s in columns)
    {
        sSQL += " or " + tables[0] + "." + s + " <> " + tables[1] + "." + s;
    }

    return sSQL;
}

private void Form1_Load(object sender, EventArgs e)
{
    OracleConnection oc = new OracleConnection(
        "User Id=scott;Password=tiger;Data Source=XE");
    oc.Open();

    string[] tables = {"t1", "t2"};
    string[] columns = {"name", "age"};

    string sSQL = OraText("id", tables, columns);
    OracleCommand oracmd = new OracleCommand(sSQL, oc);
    OracleDataReader reader = oracmd.ExecuteReader();
    while (reader.Read())
    {
        Console.WriteLine(reader.GetValue(0) + " "
            + reader.GetValue(1) + " " +reader.GetValue(2));
    }

    oc.Close();
}


控制台输出:

1 ram 35

关于c# - 从两个具有相同主键的表中获取不同的列值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30072041/

10-09 07:18
查看更多