Sql server 是否可以在CTE内部使用Declare?

Sql server 是否可以在CTE内部使用Declare?,sql-server,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 但它显示了一个错

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

;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
但它显示了一个错误:

味精156,第15级,状态1,第909行
关键字“declare”附近的语法不正确


我想使用一个变量来保存joindate值,并根据它返回值。如何使用?

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

在这种情况下,似乎您甚至不需要CTE或类型转换。此查询将告诉您该员工已工作了多少天,这似乎是目标:

select datediff(dd, joningdate, getdate()) from employeedetail

为什么您不能在select查询中计算,即cte为(…)的
从cte中选择datediff(dd,joindate,getdate())
?是的,我可以根据您的建议这样做,但我想通过使用variable来实现这一点,但问题是:为什么您要将看起来是
DATE
DATETIME
列的内容转换为
VARCHAR(50)
首先,然后你想在
DATEDIFF
函数中使用它——这毫无意义!只需将列保留为
DATE
/
DATETIME
并将
DATEDIFF
应用于它……大多数人都会认为
employeedetail
是一个包含多行的表,因此,CTE也是如此(可能)返回多行。那么,将CTE返回的
joindate
赋值给标量变量有什么意义呢?