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

后端 未结 5 546
耶瑟儿~
耶瑟儿~ 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 + '%'''
    
    0 讨论(0)
  • 2021-01-13 07:25
    SET @search = '%' + @search 
    SET @SQLQuery = 'SELECT * FROM [tblApps] WHERE [firstName] LIKE ' + @search + '%'
    
    0 讨论(0)
  • 2021-01-13 07:26
    declare @Cmd nvarchar(2000)
    declare @eName varchar(10)
    set @eName='a'
    set @Cmd= 'select * from customer1 where name LIKE '''+'%' +@eName+ '%' + ''''
    print @Cmd
    EXECUTE sp_executesql @Cmd
    
    0 讨论(0)
  • 2021-01-13 07:28

    This worked for me!

    SET @search = '''%' + @search + '%'''
    SET @SQLQuery = 'SELECT * FROM [tblApps] WHERE [firstName] LIKE' + @search
    EXEC sp_executesql @SQLQuery
    
    0 讨论(0)
  • 2021-01-13 07:29
    SET @SQLQuery = 'SELECT * from [tblApps] WHERE [firstName] LIKE ''%'' + @search + ''%'''
    exec sp_executesql @query=@SQLQuery, @params=N'@search nvarchar(96)', @search=@search
    

    The only difference from this version as compared to the others is that the dynamic execution of the sql is in fact parameterized which mitigates sql injection a bit.

    0 讨论(0)
提交回复
热议问题