I've a query:
DECLARE @sql2 nvarchar(max), @counts int, @maxdate date;
SELECT @maxdate=isnull(Max(btestDateResultBack),'01/01/1900') FROM BloodTests
PRINT @maxdate
print @maxdate
SET @sql2 = 'SELECT CONVERT(GROUP_CONCAT(btestDonor) USING utf8) AS DonorIDs,
'+CAST(@maxdate AS varchar(20))+', count(*) AS Count
FROM blood_tests WHERE btestResult = 1
AND btestDateResultBack >''''' +convert(varchar(30), @maxdate, 121)
+''''''
SET @sql2 = 'SELECT * From openquery(MYSQL_donors, '''+@sql2+''')'
EXEC sp_executesql @sql2
that returns the DonorIDs and Count columns correctly, but the column with the variable '+CAST(@maxdate AS varchar(20))+' returns the date as an alias to a column (see image below).
Using @maxdate in the WHERE clause works just fine.
How can I use @maxdate in the body of the SELECT statement?
I've seen plenty of answers on how can I use this variable in a WHERE clause, but I haven't seen one discussing adding it to the SELECT statements select list.
Final Working Solution
DECLARE @sql nvarchar(max) ,@sql2 nvarchar(max) , @sql3 nvarchar(max) , @counts int , @bloodtestdonors int , @maxdate date;
--Find and delete bloodtests from today SELECT @maxdate = isnull(Max(btestDateResultBack),'1900-01-01') FROM BloodTests;
PRINT @maxdate;
SET @sql2 = 'SELECT CONVERT(GROUP_CONCAT(btestDonor) USING utf8) AS DonorIDs, '''''+CAST(@maxdate AS varchar(30))+''''' AS Date, count(*) AS Count FROM blood_tests WHERE btestResult = 1 AND btestDateResultBack >'''''+convert(varchar(30), @maxdate, 121)+''''''
SET @sql2 = 'SELECT * From openquery(MYSQL_donors, '''+@sql2+''')'
EXEC sp_executesql @sql2
Thanks @bielawski and @Prdp for the help and clarification. I appreciate it. Thanks @stan-shaw for the code formatting.
...AS DonorIDs, '+CAST(@maxdate AS varchar(20))+' as SomeDate...
– scsimon