2012-12-07 22 views
1

我想獲取特定部分和其他搜索條件下的學生列表。我這樣做: -使用Intersect從兩個表獲取記錄

declare @sectionId int, @name varchar 
select @sectionId=23 
select @name='a' 

select UserId, FirstName from StudentMaster 
Where FirstName Like @name and UserId IN 
(
    select UserId from StudentMaster 
    Intersect 
    select StudentId from StudentInSections where [email protected] 
) 

但它沒有給出正確的答案。如果我只寫了Userid條件,它的工作正常,但我必須得到整個搜索條件的列表。 有人幫我嗎?

+0

'intersect'在這裏看起來絕對是多餘的。這應該是一樣的:'...和UserId IN(從StudentInSections中選擇StudentId,其中SectionId = @ sectionId)''。所以你的問題似乎與'intersect'無關。 –

回答

0

問題是LIKE操作數。如果@name'a'這將只返回名稱爲'a''A'的學生。如果你想學生的姓名從「a」你必須添加一個通配符「%」

FirstName LIKE 'a%' 

(如MS訪問某些SQL方言使用通配符「*」,而不是「%」。)

注對區分大小寫/不敏感的搜索。根據SQL方言和用於該列的排序規則,搜索將區分大小寫。如果你不想做一個區分大小寫的搜索(例如,你希望找到的學生,其名稱以「A」或「A」開頭),你可以這樣做:

UPPER(FirstName) LIKE 'A%' 

或SQL-服務器

FirstName COLLATE UTF8_GENERAL_CI LIKE '%a' 

其中CI表示不區分大小寫。

+0

謝謝你的幫助。 – mitali

0
select sm.UserId, sm.FirstName from StudentMaster sm 
    inner join StudentInSections ss on ss.StudentId = sm.UserId 
Where sm.FirstName Like @name 
    and ss.SectionId = @sectionId 

類似的東西應該工作。你只需要學習如何使用內部連接。