mnoisette
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,GETD ATE())
set @years = DATEDIFF(YY,HireDate,GETDA TE())
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?
Here is my SQL statement:
USE Northwind
GO
declare @age VARCHAR(4), @years VARCHAR(4)
set @age = DATEDIFF(YY,BirthDate,GETD
set @years = DATEDIFF(YY,HireDate,GETDA
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?
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?
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Makes sense...
Got it!
Thanks.
Got it!
Thanks.
set @age = DATEDIFF(YY,BirthDate,GETD
set @years = DATEDIFF(YY,HireDate,GETDA
You can solve this by rewriting the WHERE criteria:
Open in new window