Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to embed a variable in a string?

Tags:

sql

sql-server

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?

like image 243
dmx28192 Avatar asked May 20 '26 11:05

dmx28192


1 Answers

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

like image 58
XAMT Avatar answered May 23 '26 02:05

XAMT