Click here to Skip to main content
14,392,692 members

List the name of employees within a given age range

RealWork asked:

Open original thread
I have to list the names of the employees who fall within a given age range. I am new in learning to use variables/parameters in SQL, and I am having a hard time to get an output.

I don't know how to set a variable so a user can enter a age range and then get the names of the employees who fall within that range.


I am getting this error when I run this query

Incorrect syntax near the keyword 'with'. If this statement is a common table expression, an xmlnamespaces clause or a change tracking context clause, the previous statement must be terminated with a semicolon.
Msg 102, Level 15, State 1, Line 72


What I have tried:

Declare @AgeRange int
Set @AgeRange = DATEDIFF(YEAR, '1946-06-08', GETDATE()) 

WITH AgeData as 
  (
    SELECT FirstName, LastName,
    DateOfBirth, 
    DATEDIFF(YEAR, DateOfBirth, GETDATE()) AS AGE
    FROM ptWMember as wm
    JOIN ptWorkingCertification as wc on wc.PK = wm.fkptWCertification
  ),
  GroupAge AS
(
  SELECT FirstName, LastName,
         DateOfBirth,
         Age,
         CASE
             WHEN @AgeRange < 30 THEN 'Under 30'
             WHEN @AgeRange BETWEEN 31 AND 40 THEN '31 - 40'
             WHEN @AgeRange BETWEEN 41 AND 50 THEN '41 - 50'
             WHEN @AgeRange > 50 THEN 'Over 50'
             ELSE 'Invalid Birthdate'
         END AS [Age Groups]
  FROM AgeData
 )
SELECT FirstName, LastName
FROM AgeData
Tags: SQL, SQL-Server

Preview



When answering a question please:
  1. Read the question carefully.
  2. Understand that English isn't everyone's first language so be lenient of bad spelling and grammar.
  3. If a question is poorly phrased then either ask for clarification, ignore it, or edit the question and fix the problem. Insults are not welcome.
  4. Don't tell someone to read the manual. Chances are they have and don't get it. Provide an answer or move on to the next question.
Let's work to help developers, not make them feel stupid.
Please note that all posts will be submitted under the The Code Project Open License (CPOL).




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100