3

I am running the following SQL in SEDE (StackExchange Data Explorer). This SQL can specify the date and time for CreationDate, and the default value uses the value of @MonthsAgo variable.

This works fine if you enter a date and time, but you get the following error with the @MonthsAgo variable:

Conversion failed when converting date and/or time from character string.

https://data.stackexchange.com/stackoverflow/revision/1187086/1459772

declare @MonthsAgo date = cast(dateadd(month, -2, getdate()) as date)
declare @since date = ##SinceDate:string?@MonthsAgo##

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

How can I search using this variable?

1
  • Please mark the answer as an accepted if it was helpful or comment it if-else. Commented Apr 16, 2020 at 13:46

2 Answers 2

1

The ##SinceDate:string?@MonthsAgo## is pseudocode and It isn't running in SQL Server.

StackExchange Data Explorer uses ##xxx## format to replace with Parameters that you enter on Parameter Section.

In a nutshell, If you want to convert NVarChar or Varchar to DateTime (or Date) Type :

Declare @since varchar(20)
set @since = '08-12-2012 10:15:10'
select convert(datetime, @since , 101)

Orginal Source : Here

Sign up to request clarification or add additional context in comments.

2 Comments

Where does that conversion apply? I tried to convert the two input values to strings and convert them to DATETIME later, but that is caused same error.
Parameters will replace on the server when you hit the Run Query key.
0

You can use @MonthsAgo parameter at the query without specifying a type. If you use any type as a string, SEDE treats it like a string, not a parameter name.

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

1 Comment

However, that query does not return posts dated after 2019-12-31 when you specify 2019-12-31. data.stackexchange.com/stackoverflow/revision/1187659/1460544/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.