How to use LIKE in a t-sql dynamic statement in a stored procedure?

后端 未结 5 550
耶瑟儿~
耶瑟儿~ 2021-01-13 06:47

I\'m trying to use the LIKE keyword with the % wildcards wrapping the parameter, but I\'m not sure how to get the % characters into the statement without breaking it. Right

5条回答
  •  无人及你
    2021-01-13 07:20

    The % characters have to be in the search string...

    SET @search = '%' + @search + '%'
    SET @SQLQuery = 'SELECT * FROM [tblApps] WHERE [firstName] LIKE @search'
    

    Note that the following would also work, but introduces potential for a SQL injection vulnerability...

    -- DON'T do this!
    SET @SQLQuery = 'SELECT * FROM [tblApps] WHERE [firstName] LIKE ''%' + @search + '%'''
    

提交回复
热议问题