0

The query below works if the 2 dates are hard coded, however, I would like to replace them with the 2 variables @FirstDayM and @LastDayM. When I do so, it returns the following error

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

DECLARE @sql varchar(max)
DECLARE @FirstDayM DATE = DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE())-1, 0)
DECLARE @LastDayM DATE = DATEADD(MONTH, DATEDIFF(MONTH, -1, GETDATE())-1, -1);

    SELECT @sql = Coalesce(@sql + ' UNION ALL ', '') + 'SELECT COUNT(C1CustID) AS CertsCount, ''' + QuoteName(name)+  ''' as DBname FROM ' + QuoteName(name) + '.dbo.T_C1CustCourse'+
    ' WHERE C1CertificationDate_N >= '+'''2018-01-01'''+' AND C1CertificationDate_N <= '+'''2018-01-31'''
    FROM   sys.databases WHERE database_id > 4 AND state = 0;

EXEC (@sql);

1 Answer 1

2

Use sp_executesql. Always. It makes it easy to put parameters into queries. Even if the dynamic query does not start with the parameter, you might decide to add one later.

declare @sql nvarchar(max);
declare @firstDayM date;
declare @lastDayM date;

set @firstDayM = ?;
set @lastDayM = ?;

SELECT @sql = Coalesce(@sql + ' UNION ALL ', '') + '
SELECT COUNT(C1CustID) AS CertsCount, ''' + QuoteName(name)+  ''' as 
DBname
FROM ' + QuoteName(name) + '.dbo.T_C1CustCourse' + '
WHERE C1CertificationDate_N >= @FirstDayM AND C1CertificationDate_N 
<= @LastDayM'
FROM sys.databases
WHERE database_id > 4 AND state = 0;

EXEC sp_executesql @sql, N'@FirstDayM date, @lastDayM date',
     @FirstDayM=@FirstDayM, @lastDayM=@lastDayM;
Sign up to request clarification or add additional context in comments.

4 Comments

tnx a lot, does the @sql variable need to be declared too? I declared it NVARCHAR(MAX), however, it returns the following error 'Error converting data type nvarchar to date'
@DeepDiver . . . Yes, of course. I missed copying it the first time.
Tnx again, after declaring @sql nvarchar(max), it returns the following error 'Msg 8114, Level 16, State 5, Line 0 Error converting data type nvarchar to date.'
It works, there are an unspotted @ symbol missing in the last line, @LastDayM=LastDayM

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.