是否可以在CTE中使用Declare?

时间:2017-02-01 05:47:44

标签: sql-server

我正在尝试执行以下代码:

;with cte  as 
(  
    select 
        convert(varchar(50), joiningdate, 101) as joindate 
    from 
        employeedetail   
)   
declare @dateuse varchar(200)=cte.joindate  
select datediff(dd, @dateuse, GETDATE()) 
from cte

但它显示错误:

  

Msg 156,Level 15,State 1,Line 909
  关键字'声明'。

附近的语法不正确

我想使用包含joindate值的变量并根据它返回值。怎么样?

1 个答案:

答案 0 :(得分:0)

您只能在脚本,过程或UDF中使用declare。不能在查询或视图中使用。

在这种情况下,您似乎甚至不需要CTE或类型转换。此查询将告诉您员工周围的天数,这似乎是目标:

select datediff(dd, joningdate, getdate()) from employeedetail
相关问题