2016-04-27 58 views
0

我試圖使用comboboxdatagridview上創建篩選器。 我想要做的是過濾datagridview中的過濾數據。 我有7個comboboxes過濾。例如,第一個combobox是爲年,然後我仍然想要過濾搜索到年級,然後到部分等。因此,用戶將能夠從數據庫中排序或過濾他的搜索。如何從SQL Server中篩選年齡

到目前爲止,我有我的存儲過程代碼,並在組合框中試過。 SchoolYear,Grade,section,Gender,, status, Account過濾效果很好..除了年齡,我設置我的查詢來自動計算年齡而不保存到數據庫中,現在我的問題是過濾年齡。

我這樣做了我的存儲過程。

ALTER PROCEDURE [dbo].[uspYearGradeFilter] 
    @Year Nvarchar(20) = NULL, 
    @Grade Nvarchar(20) = NULL, 
    @Section Nvarchar(20) = NUll, 
    @Gender Nvarchar(20) = NULL, 
    @Status Nvarchar(20) = NULL, 
    @Status2 Nvarchar(20) = NULL, 
    @Age Nvarchar(20) = NULL 
AS 
BEGIN 
    SET NOCOUNT ON; 

    SELECT 
     si.StudentID, SI.Surname, SI.FirstName, SI.MiddleName, 
     si.Gender, si.BirthDay, SI.TelNum, 
     Birthday, getdate() AS [Today], 
     Datediff(yy, BirthDay, getdate()) - 
      CASE 
       WHEN DATEADD(YY, DATEDIFF(YY, BirthDay, getdate()), BirthDay) > GETDATE() 
        THEN 1 
        ELSE 0 
      END AS [age] 
    FROM 
     StudentInformation SI 
    JOIN 
     StudentHistory SH ON SI.StudentID = SH.StudentID 
    WHERE 
     sh.SchoolYear LIKE COALESCE('%'+ @Year+'%', sh.SchoolYear) 
     AND sh.Levels LIKE COALESCE('%' + @Grade + '%', sh.Levels) 
     AND SI.Gender LIKE COALESCE('%' + @Gender + '%', si.gender) 
     AND SH.Section LIKE COALESCE('%' + @Section + '%', sh.Section) 
     AND Si.Status LIKE COALESCE('%' + @Status + '%', si.status) 
     AND Sh.Status2 LIKE COALESCE(@Status2 + '%', sh.status2) 
     AND [Age] LIKE COALESCE('%' + @Age + '%', [Age]) 
END 

但我得到一個錯誤:

Msg 207, Level 16, State 1, Procedure uspYearGradeFilter, Line 42
Invalid column name 'Age'

可有人請幫我解決這個問題?謝謝

+0

邊注:您可以在子查詢中,雖然使用它爲什麼地球上**您使用'爲nvarchar(20)**'像一個參數'@ Year'這顯然** **是數值?請始終使用*最合適的*數據類型 - 對數值使用數字類型,對日期和時間使用日期和時間類型 - 不只是所有內容的字符串! –

+0

@marc_s - 你不知道現代風格是每一個變量被聲明爲字符串,然後有一個'.ToString()'每當它被使用? – Hogan

回答

2

您不能在立即WHERE子句中使用列別名。

SELECT * FROM 
(
    SELECT 
     si.StudentID, 
     SI.Surname, 
     SI.FirstName, 
     SI.MiddleName, 
     si.Gender, 
     si.BirthDay, 
     SI.TelNum 
     getdate() AS [Today], 
     Datediff(yy,BirthDay,getdate()) - 
        CASE 
         WHEN DATEADD(YY, DATEDIFF(YY,BirthDay,getdate()),BirthDay) > GETDATE() 
          THEN 1 
         ELSE 
          0 
        END AS [age] 
    FROM StudentInformation SI 
    JOIN StudentHistory SH 
     ON SI.StudentID = SH.StudentID 
    WHERE 
     sh.SchoolYear LIKE COALESCE('%'+ @Year+'%', sh.SchoolYear) 
     AND sh.Levels LIKE COALESCE('%' + @Grade + '%', sh.Levels) 
     AND SI.Gender LIKE COALESCE('%' + @Gender + '%', si.gender) 
     AND SH.Section LIKE COALESCE('%' + @Section + '%', sh.Section) 
     AND Si.Status LIKE COALESCE('%' + @Status + '%', si.status) 
     AND Sh.Status2 LIKE COALESCE(@Status2 + '%', sh.status2) 
) t 
WHERE [Age] LIKE COALESCE('%' + @Age + '%', [Age]) 
+0

嗨費利克斯,當我嘗試你的代碼時出現錯誤。它說'專欄'生日'被多次指定爲't'。 ' –

+0

刪除子問題中的第二個生日。 –

+0

謝謝菲利克斯,它完美的作品:-) –