Click here to Skip to main content
15,886,422 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hello. I am trying to Select values from 2 tables.
My 1st table(Student_Data) is as follows:
HTML
USN       |Name    |FName    |Dept    |Branch    |Sem
001        abc      ABC       BE       CS         3
002        xyz      XYZ       BE       CS         3
003        def      DEF       BE       CS         4
004        pqr      PQR       BE       CS         5

My 2nd table(Course_Data) is as follows:
HTML
CC       |C_Title  |Dept    |Branch    |Sem  |Crdits
sub1       C        BE       CS         3      5
sub2       C++      BE       CS         3      5
sub1       Math     BE       CS         4      5
sub1       Java     BE       CS         5      5

I want my result as follows : (When user enters USN as 001,Dept as BE, Branch as CS and Sem as 3)
HTML
USN       |Name    |FName     |CC       |C_Title    |Crdits
001        abc      ABC        sub1      C           5
001        abc      ABC        sub2      C++         5

I tried and I was able to built the following Query :
SQL
SELECT * FROM (SELECT Student_Data.USN, Student_Data.Name, Student_Data.FName, Course_Data.CC, Course_Data.Credits FROM Student_Data INNER JOIN Course_Data ON Student_Data.Dept=Course_Data.Dept AND Student_Data.Branch=Course_Data.Branch) WHERE USN = '" + TextBox1.Text + "' ORDER BY CC 

I am getting error at WHERE Clause as Incorrect Syntax.
Please Help me out.
Thank you.
Posted
Updated 26-Apr-15 19:56pm
v2
Comments
Sinisa Hajnal 27-Apr-15 2:48am    
You need to add alias for the subselect just before WHeRE like this ) a WHERE...

But Griffs solution is cleaner and the advice sound. NEVER trust user input.

1 solution

First, Do not concatenate strings to build a SQL command. It leaves you wide open to accidental or deliberate SQL Injection attack which can destroy your entire database. Use Parametrized queries instead.

Then try something like this:
SQL
SELECT s.USN, s.Name, s.FName, c.CC, c.C_Ttile, c.Credits 
FROM Student_Data s
INNER JOIN Course_Data c
ON s.Dept=c.Dept AND s.Branch=c.Branch
WHERE s.USN=@USN 
ORDER BY c.CC

Don't forget to add the @USN parameter to your SqlCommand object and set it's value to the textbox content!
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900