简体   繁体   中英

MS sql inner join

I have two tables one is Subjects and UserDetails Columns of those two tables:

  • Subjects (RegNo,IndexNo,Subject_1,Subject_23,Subject_3,Subject_4) and
  • UserDetails (Name,DOB,RegNo,Address,ID)

I want to get Name , DOB , RegNo , Address , ID from UserDetails and Index from Subjects acoording to a specific subject .i created a query but it is not working _subject is the string variable which contains the subject name

SELECT UserDetails.Name,UserDetails.DOB,
      UserDetails.RegNo,UserDetails.Address, UserDetails.ID,
Subjects.IndexNo 
FROM UserDetails
INNER JOIN Subjects  ON UserDetails.RegNo = Subjects.RegNo 
WHERE Subjects Subject_1 
   OR Subject_2 
   OR Subject_3 OR Subject_4 ='"+_subject+"'"

You will probably figure this out on your own, but you need to specify each part of the WHERE clause, like this:

WHERE Subjects.Subject_1 = '"+_subject+"'"
OR Subjects.Subject_2 = '"+_subject+"'"
OR Subjects.Subject_3 = '"+_subject+"'"
OR Subjects.Subject_4 = '"+_subject+"'"

Your where clause is invalid.

Try

WHERE
   Subject_1 = '"+_subject+"' 
   OR Subject_2 = '"+_subject+"'
   OR Subject_3 = '"+_subject+"'
   OR Subject_4 = '"+_subject+"'"

I'm assuming that your _subject string has been sanitized and that a user couldn't just use it for a SQL injection attack ...

Are you trying to match any of the subjects for UserDetails against a string stored in a variable?

Try this

DECLARE @subject varchar(20) = 'subjectstringvalue'; --variables are declared like this in T-sql
SELECT
ud.Name
,ud.DOB
,ud.RegNo
,ud.Address
,ud.ID
,s.IndexNo 

FROM UserDetails AS ud
INNER JOIN Subjects AS s
    ON ud.RegNo = s.RegNo 

WHERE s.Subject_1 = @subject --variables are used like this in T-sql
OR Subject_2 = @subject
OR Subject_3 = @subject
OR Subject_4 = @subject

Instead just create a simple stored procedure like below and pass your subject value as parameter.

CREATE PROC GetDetails
(
    @Subject VARCHAR(10)
)
BEGIN       
    SELECT UserDetails.Name,UserDetails.DOB,
          UserDetails.RegNo,UserDetails.Address, UserDetails.ID,
    Subjects.IndexNo 
    FROM UserDetails
    INNER JOIN Subjects  ON UserDetails.RegNo = Subjects.RegNo 
    WHERE Subject_1 = @Subject 
       OR Subject_2 = @Subject
       OR Subject_3 = @Subject
END 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM