Search code examples
sqlsql-serverdynamiccode-injection

How to write a '1=1' within dynamic sql


Can someone please correct this?

declare @g varchar(max)
set @g = 'select *
from person.person
where firstname like '%t' '
set @g = @g + 'or firstname  like''' +('a'= 'a')+ ''''

exec (@g)

Solution

  • Your base query should have 1=1

    set @g = 'select *
    from person.person
    where 1=1 '
    set @g = @g + 'and firstname like ''%t'' '
    set @g = @g + 'or firstname  like ''' +('a'= 'a')+ ''''
    

    If you need to group the conditions they all need to be together:

    set @g = @g +'(firstname like ''%t%'' or firstname like ''%a'')'