I was trying to create a dynamic SQL query, But unfortunately it shows an error:
Msg 245, Level 16, State 1, Line 14
Conversion failed when converting the varchar value 'select count (s.ID), count (distinct (s.ID)) from SimulationVisit SV inner join Students on s. ID=SV. Student ID Inner join Activity Context AC on AC. ID=SV. ActivityContextID WHERE (AC. TenantID = ' to data type int.
My code
declare @DateRangeStart [DATETIME2](7),
@DateRangeEnd [DATETIME2](7),
@TenantID [SMALLINT] ,
@ActivityContextID [INT],
@StudentID [INT] = NULL
'select count(s.ID),count(distinct(s.ID))
from SimulationVisit SV
inner join Student s on s.ID = SV.StudentID
inner join ActivityContext AC on AC.ID = SV.ActivityContextID
where (AC.TenantID = ' + @TenantID + ' OR @TenantID is null)
and (AC.ID =' + @ActivityContextID + ')
and (SV.StudentID = ' + @StudentID + ')';
Please help me to fix this issue