使用select查询中的值声明变量

时间:2015-11-26 05:21:47

标签: sql sql-server tsql adventureworks

DECLARE @age DATETIME
SET @age = (GETDATE() - emp.Birthdate)

SELECT 
    emp.BusinessEntityID, emp.BirthDate, @age
FROM 
    HumanResources.Employee AS emp
WHERE 
    emp.OrganizationLevel > = 3 
    AND ((GETDATE() - emp.Birthdate) BETWEEN '1930-01-01 00:00:00.000' AND '1940-01-01 00:00:00.000')

正如专业人士所知,这是行不通的,我希望能够显示年龄在30-40岁之间的人的身份,日期和年龄。声明@age是我的问题。我尝试使用substring(getdate...), 2, 2),但它似乎无法正常工作。有任何想法吗?感谢

5 个答案:

答案 0 :(得分:1)

此时您将值设置为@age

SET @age = (GETDATE() - emp.Birthdate)

没有emp

您只需执行以下查询:

SELECT emp.BusinessEntityID, emp.BirthDate, (GETDATE() - emp.Birthdate) AS Age
FROM HumanResources.Employee AS emp
WHERE emp.OrganizationLevel > = 3 AND
      (GETDATE() - emp.Birthdate) BETWEEN '1930-01-01 00:00:00.000' AND '1940-01-01 00:00:00.000')

答案 1 :(得分:0)

您可以使用Datediff功能查找2个日期之间的确切差异

SELECT 
     datediff(yyyy,GETDATE(),date)
FROM 
     [PRGX_AS_SandBox].[dbo].[Test_SO]

答案 2 :(得分:0)

首先,您不能设置具有多个值的标量变量。 其次,为此你根本不需要变量。 你可以这样做:

SELECT BusinessEntityID, BirthDate, DATEDIFF(Year, BirthDate, GETDATE()) As Age
FROM HumanResources.Employee 
WHERE OrganizationLevel > = 3 
AND DATEDIFF(Year, BirthDate, GETDATE()) BETWEEN 30 AND 40

注意:这不会给出确切的年龄。要获得确切的年龄,您可以使用this post中的答案。我认为最好的答案是this answer dotjoe

答案 3 :(得分:0)

我认为您正在尝试让员工年龄在30到40岁之间,您只需使用DateDiff功能执行此操作,如下所示:

SELECT BusinessEntityID,BirthDate,DATEDIFF(YEAR,BirthDate,GETDATE()) AS Age 
FROM HumanResources.Employee 
WHERE DATEDIFF(YEAR,BirthDate,GETDATE()) BETWEEN 30 AND 40 
ORDER BY Age ASC    

答案 4 :(得分:0)

无需在查询中使用变量。您可以按照以下步骤执行此操作:

SELECT t.BusinessEntityID, t.BirthDate, t.Age
FROM
(SELECT emp.BusinessEntityID, emp.BirthDate, CAST(datediff(DAY, emp.Birthdate, GETDATE()) / (365.23076923074) as int) as 'Age'
FROM HumanResources.Employee AS emp
WHERE emp.OrganizationLevel > = 3) t
WHERE t.Age >= 30 and t.Age <=40