I’m trying to print out Tables from the DB that have the EntityId column equals to DataclassId column here is the code
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";
SqlDataReader rootTables_List = null;
SqlConnection conn = new SqlConnection(connect);
conn.Open();
SqlCommand s_cmd = new SqlCommand("SELECT * FROM sys.Tables WHERE EntityId = DataclassId", conn);
rootTables_List = s_cmd.ExecuteReader();
while (rootTables_List.Read())
{
string test = rootTables_List[0].ToString();
Console.WriteLine("ROOT TABLES ARE {0}", test);
}
rootTables_List.Close();
conn.Close();
}
but it keeps saying that these columns are invalid though when I printed out all the columns in the DB “syscolumns” they were there…
Can anyone tell me why I’m getting such an error?
EDIT
What I really want is to query the db TacOps_4_0_0_4_test not the system. I just realized that
EDIT 2
Here is an example of the Tables in my 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
The output should be
Table_1
Table_3
I think I may understand what you’re trying now based on your comment to Frederik’s answer
It sounds like EntityId and Dataclassid are columns in a table (or tables) that you have in your database and you want to find the rows from those tables that contain the same value in both those columns??
If that’s the case, you are querying sys.Tables incorrectly – you’d need to query the specific tables directly i.e.
Can you clarify?
Edit:
You can find all the tables that contain both those columns using this:
From this, you could either iterate round each table and run the query to find rows that match on EntityId/DataClassId values – could insert into a temp table and return 1 resultset at the end.
OR, you could create a view to UNION all the tables together and then query that view (would need to update the view each time you added a new table).
OR, you could do some dynamic SQL generation based on the above to generate a SELECT statement on-the-fly to UNION all the tables together.
Update:
Here’s a generic way to do it in pure TSQL – this way means if new tables are added it will automatically include them:
If you don’t need it to be dynamic, change the above EXECUTE to a PRINT to see the SQL it generates, and then create a view from it. You can then SELECT from that view.
Of course, you could either loop round each table 1 by 1 as you are trying.