Sql 如何在字符串中嵌入变量?

Sql 如何在字符串中嵌入变量?,sql,sql-server,Sql,Sql Server,我正在SEDE(StackExchange数据资源管理器)中运行以下SQL。 此SQL可以指定CreationDate的日期和时间,默认值使用@MonthsAgo变量的值 如果您输入了日期和时间,这可以正常工作,但是@MonthsAgo变量会出现以下错误: 从字符串转换日期和/或时间时,转换失败 如何使用此变量进行搜索?该###SinceDate:string?@MonthsAgo##是伪代码,不在SQL Server中运行 StackExchange数据资源管理器使用##xxx##格式替换为

我正在SEDE(StackExchange数据资源管理器)中运行以下SQL。 此
SQL
可以指定
CreationDate
的日期和时间,默认值使用
@MonthsAgo
变量的值

如果您输入了日期和时间,这可以正常工作,但是
@MonthsAgo
变量会出现以下错误:

从字符串转换日期和/或时间时,转换失败

如何使用此变量进行搜索?

###SinceDate:string?@MonthsAgo##
是伪代码,不在SQL Server中运行

StackExchange数据资源管理器使用
##xxx##
格式替换为在参数部分输入的参数

简而言之,如果要将
NVarChar
Varchar
转换为
DateTime
(或
Date
)类型:


原始来源:

您可以在查询中使用
@MonthsAgo
参数,而无需指定类型。如果使用任何类型作为字符串,SEDE将其视为字符串,而不是参数名

declare @MonthsAgo date = cast(dateadd(month, -2, getdate()) as date)

select vote.PostId, post.Score, post.CreationDate from votes vote
  inner join posts post on post.Id = vote.PostId
  where post.CreationDate >= ##SinceDate?@MonthsAgo## and Tags like '%java%'
order by post.Score desc

这种转换适用于哪里?我尝试将两个输入值转换为字符串,稍后再将其转换为DATETIME,但也就是说,当您点击Run Query键时,服务器上的参数将被替换。但是,当您指定
2019-12-31
时,该查询不会返回日期在2019-12-31之后的帖子。如果答案有帮助,请将其标记为已接受,否则请予以评论。
Declare @since varchar(20)
set @since = '08-12-2012 10:15:10'
select convert(datetime, @since , 101)
declare @MonthsAgo date = cast(dateadd(month, -2, getdate()) as date)

select vote.PostId, post.Score, post.CreationDate from votes vote
  inner join posts post on post.Id = vote.PostId
  where post.CreationDate >= ##SinceDate?@MonthsAgo## and Tags like '%java%'
order by post.Score desc