Shaiwal Tripathi Shaiwal Tripathi - 1 year ago 76
SQL Question

How to parameterize query with like operator in Sql Server

I am trying to parameterize Sql Query with like operator but it's not working. Both Search Criteria and Search text will be through Variable. Here what I am doing

declare @Query nvarchar(500), @SearchBy nvarchar(50) = 'PtName', @SearchText nvarchar(50) = 'Sh'
set @Query = 'select Id, PtName, Y, M, D, Sex, PtCode, ReceiptDate, ReferBy, RefDrCd, PtTitle, NetAmount, IncentiveAmount, PaidAmount, DueAmount, Investigation, LabCode, LabName, DiscAmount, PNo FROM DiagMain where '[email protected]+' like '[email protected]+' %'
exec(@Query)


Please Help.

Answer Source
DECLARE @Query NVARCHAR(500), @SearchBy NVARCHAR(50) = 'PtName', @SearchText NVARCHAR(50) = 'Sh'
SET @Query = 'select Id, PtName, Y, M, D, Sex, PtCode, ReceiptDate, ReferBy, RefDrCd, PtTitle, NetAmount, IncentiveAmount, PaidAmount, DueAmount, Investigation, LabCode, LabName, DiscAmount, PNo  FROM DiagMain where '[email protected]+' like '''[email protected]+'%'''

PRINT @Query
EXEC(@Query)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download