Link to home
Start Free TrialLog in
Avatar of mnoisette
mnoisetteFlag for United States of America

asked on

SQL Variables used with a SELECT Clause

I have a SELECT that I want to use a variable with for an expression, but the variable(s) contains columns from my database.

Here is my SQL statement:

USE Northwind
GO
declare @age VARCHAR(4), @years VARCHAR(4)
set @age = DATEDIFF(YY,BirthDate,GETDATE())
set @years = DATEDIFF(YY,HireDate,GETDATE())

SELECT FirstName, Birthdate, Hiredate
FROM Employees
WHERE (@age + @years) >85

I receive the following errors:

Msg 207, Level 16, State 1, Line 4
Invalid column name 'BirthDate'.
Msg 207, Level 16, State 1, Line 5
Invalid column name 'HireDate'.

What am I doing wrong?
Avatar of Vitor Montalvão
Vitor Montalvão
Flag of Switzerland image

What am I doing wrong?
This is wrong:
set @age = DATEDIFF(YY,BirthDate,GETDATE())
 set @years = DATEDIFF(YY,HireDate,GETDATE())

You can solve this by rewriting the WHERE criteria:
SELECT FirstName, Birthdate, Hiredate
FROM Employees
WHERE (DATEDIFF(YY,BirthDate,GETDATE()) + DATEDIFF(YY,HireDate,GETDATE())) >85

Open in new window

Avatar of mnoisette

ASKER

That's how I originally wrote it and it works fine.
I wanted to write it with a variable if that were possible.
Why can't I define the expression with a variable?
ASKER CERTIFIED SOLUTION
Avatar of Vitor Montalvão
Vitor Montalvão
Flag of Switzerland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Makes sense...
Got it!
Thanks.