I am trying to create a dynamic query in sql-server as a string, it works perfect if the @SupervisorId or @UnitId is null, however when i test it like below i get this error (meaning if @SupervisorId or @UnitId is not null):
Msg 102, Level 15, State 1, Line 10 Incorrect syntax near 'c33fff6'. Msg 153, Level 15, State 2, Line 14 Invalid usage of the option next in the FETCH statement. Msg 102, Level 15, State 1, Line 10 Incorrect syntax near 'c33fff6'.
what i tried:
declare @SupervisorId uniqueidentifier = null;
declare @UnitId uniqueidentifier = null;
declare @Name nvarchar(max) = null;
declare @PersonTypeId int;
declare @PageNum int;
declare @PageSize int;
declare @KW nvarchar(max);
declare @Query nvarchar(max);
declare @Query2 nvarchar(max);
declare @WhereClause nvarchar(max);
set @PageNum = 0;
set @PageSize = 50;
set @PersonTypeId = 10003;
set @UnitId = '5c33fff6-ae91-4946-92e2-50f8ae9bd6f5';
set @WhereClause = ' 1=1 ';
if (@Name is not null)
set @WhereClause =@WhereClause + ' And p.Name like N'''+'%'+cast(@Name as nvarchar(4000))+'%'+''' or p.Family like N'''+'%'+cast(@Name as nvarchar(4000))+'%'+''' ';
if(@SupervisorId is not null)
set @WhereClause = @WhereClause + ' AND p.SupervisorId in ('+ CAST(@SupervisorId as nvarchar(4000)) +') ';
if(@UnitId is not null)
set @WhereClause = @WhereClause + ' AND p.UnitId in (' + CAST(@UnitId as nvarchar(4000)) + ') ';
Set @Query = '
SELECT u.*, p.*, uu.Name as UnitName, jj.Name as JobName, pp.Name + '' '' + pp.Family as SupervisorName, s.IsActive as IsActive
FROM [Membership].Users u
LEFT JOIN [Membership].Persons p on p.ID = u.ID
INNER JOIN [kernel].BaseEntity s on s.ID = p.ID and s.IsDelete = 0
LEFT JOIN Base.Units uu on uu.ID = p.UnitId
LEFT JOIN Base.Jobs jj on jj.ID = p.JobId
LEFT JOIN [Membership].Persons pp on pp.ID = p.SupervisorId
Where '+@WhereClause+ ' and p.PersonTypeId = '+ CAST(@PersonTypeId as nvarchar(100)) +'
Order by p.Family DESC
Offset '+CAST(@PageSize as nvarchar(10))+' * ('+CAST(@PageNum as nvarchar(10))+') Rows
Fetch next '+CAST(@PageSize as nvarchar(10))+' ROWS ONLY';
set @Query2 ='
SELECT COUNT(*)
FROM [Membership].Users u
LEFT JOIN [Membership].Persons p on p.ID = u.ID
INNER JOIN [kernel].BaseEntity s on s.ID = p.ID and s.IsDelete = 0
LEFT JOIN Base.Units uu on uu.ID = p.UnitId
LEFT JOIN Base.Jobs jj on jj.ID = p.JobId
LEFT JOIN [Membership].Persons pp on pp.ID = p.SupervisorId
Where '+@WhereClause + ' and p.PersonTypeId = '+ CAST(@PersonTypeId as nvarchar(100)) +'' ;
exec (@Query);
exec (@Query2);
@queryand@query2instead of/as well as trying to execute them, the "typos" caused by the generating code should jump out at you, without having to post a question to SO. (You can print them to a console, or at least to a log at a suitable logging level)