Mouad Raizada
Mouad Raizada

Reputation: 127

How to retrive data from a table depending on two matched values from different tables

I have emp table in which empId is the primary key and another table empLogin in which the empId is a foreign key, whenever the user login the system its ID is inserted from emp table into empLogin table this empId is very important in billing and reciepting forms and I want to show the employee name instead of its ID ...

I've written these codes for this idea but it gives me an exception which is

The multi-part identifier "empLogin.empId" could not be bound

My codes are:

cmd2 = new SqlCommand("select empName from emp where emp.empId=empLogin.empId", cn);
dr2 = cmd2.ExecuteReader();
dr2.Read();
rcptEmpNametxt.Text = dr["empName"].ToString();
dr.Close();

Upvotes: 0

Views: 58

Answers (4)

Aditya
Aditya

Reputation: 2311

Something like this should work ...

SELECT TOP 1 empName
FROM EMP E
INNER JOIN EMPLOGIN EL ON E.empId = EL.empId 
ORDER BY ... DESC

The ... should be replaced with the primary key of table EMPLOGIN. I hope this helps : )

Upvotes: 0

Jaydip Jadhav
Jaydip Jadhav

Reputation: 12309

Missing JOIN between emp AND empLogin

select empName 
from emp 
INNER JOIN empLogin ON emp.empId=empLogin.empId

Upvotes: 0

inan
inan

Reputation: 188

You have to join the tables and do that, there is no join used in your inline sql statement, that's the reasons it throwing "The multi-part identifier "empLogin.empId" could not be bound" error.

Upvotes: 0

Roman Marusyk
Roman Marusyk

Reputation: 24609

The simplest way is:

cmd2 = new SqlCommand("select empName from emp, empLogin where emp.empId=empLogin.empId", cn);

but this one will be more useful:

cmd2 = new SqlCommand("select empName from emp inner join empLogin on emp.empId=empLogin.empId", cn);

Upvotes: 2

Related Questions