继续我的主题“http://stackoverflow.com/questions/3767000/invalid-column-name-though-its-there”查询选择具有类似列的表值
我想编写一个查询,选择具有ENTITYID和DataclassId列作为相同的值(跳过过程的空值)
这里的值的表是我的DB的示例
Table_1
ID Sequence Type Heigh Weight EntityId DataclassId
0 1 s 1.4 2.5 42-2c-Qi 42-2c-Qi
1 2 s 2.4 2.5 zh-km-xd zh-km-xd
2 3 s 3.4 2.5 8n-tr-l7 8n-tr-l7
Table_2
ID Data Person EntityId DataclassId
0 1 Dave 58-zj-4o 41-2c-Q7
1 2 Sara 99-op-t6 oy-7j-mf
2 3 Silve 75-qy-47 2d-74-ds
Table_3
ID Name Genre EntityId DataclassId
0 LR Ac 78-jd-o9 78-jd-o9
1 OI Dr 4t-jb-qj 4t-jb-qj
2 DH Do 7j-3e-ol 7j-3e-ol
Table_4
ID Name EntityId DataclassId
NULL NULL NULL NULL
NULL NULL NULL NULL
Table_5
ID Data Person EntityId DataclassId
0 1 Dave 58-zj-4o 41-2c-Q7
1 2 Sara 99-op-t6 oy-7j-mf
2 3 Silve fg-se-pl 2d-74-ds
输出应该
Table_1
Table_3
编辑
我还使用C#代码遍历数据库的表。但是我还没有得到正确的结果。我需要的是对rootQ变量的正确查询。
public void getRootTables_checkSP()
{
string connect = "Data Source= EUADEVS06\\SS2008;Initial Catalog=TacOps_4_0_0_4_test;integrated security=SSPI; persist security info=False;Trusted_Connection=Yes";
//Query to Select all Tables that have
//EntityId and DataclassId columns in them
string query =
"SELECT tabs.name " +
"FROM sys.tables tabs INNER JOIN sys.columns cols " +
"ON tabs.object_id = cols.object_id " +
"AND cols.name IN ('EntityId', 'DataclassId')";
int i = 0;
int j = 0; //Count for Root Tables
SqlDataReader tables_list = null;
SqlDataReader rootTables_list = null;
SqlConnection conn = new SqlConnection(connect);
SqlConnection conn2 = new SqlConnection(connect);
try
{
//Write all table that have EntityId and
//DataclassId cols into tables_list
conn.Open();
SqlCommand cmd_1 = new SqlCommand(query, conn);
tables_list = cmd_1.ExecuteReader();
while (tables_list.Read())
{
//Query to select Root Tables
//EntityId and DataclassId values are identical in Root Tables
//HERE IS WHERE I GOT STUCK AND COULDN'T FIGURE OUT THE CORRECT QUERY
string rootQ =
"SELECT * " +
"FROM " + tables_list[0] + " " +
"WHERE EntityId not NULL " +
" AND DataclassId not NULL " +
" AND EntityId != DataclassId";
try
{
//Write Root Tables into rootTables_list
conn2.Open();
SqlCommand cmd_2 = new SqlCommand(rootQ, conn2);
rootTables_list = cmd_2.ExecuteReader();
//Loop through the rootTables_list and print out the values
while (rootTables_list.Read())
{
string s = rootTables_list[0].ToString();
Console.WriteLine(s);
j++;
}
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex);
}
finally
{
Console.WriteLine();
Console.WriteLine("{0} Root Tables-Count ", j);
Console.WriteLine();
conn2.Close();
}
i++;
}
}
catch (Exception e)
{
Console.WriteLine("Error: " + e);
}
finally
{
Console.WriteLine();
Console.WriteLine("{0} All Tables-Count ", i);
Console.WriteLine();
conn.Close();
}
}
mmm ...在读完您的原始问题后,AdaTheDev提供的答案有什么问题?它和我做的一样,也是通用的。 – 2010-09-24 08:13:29
如果您的意思是tsql查询,它还返回数据库中也不共享类似列值的表。 – Reda 2010-09-24 08:35:34
每当需求变得更加清晰时,我已经更新了原始问题中的答案,并且它只返回共享匹配列值的表。所以我不知道为什么这个副本已经创建。请参阅并尝试我在这个问题上的回应。 – AdaTheDev 2010-09-24 10:57:01