0

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 '+@SearchBy+' like '+@SearchText+' %'
    exec(@Query)

Please Help.

1
  • It would help us if you gave the error message it's giving. It would help you if you first print any SQL you've assembled by string concatenation and see if it looks reasonable. Commented Aug 16, 2017 at 8:52

1 Answer 1

4
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 '+@SearchBy+' like '''+@SearchText+'%'''

PRINT @Query
EXEC(@Query)
Sign up to request clarification or add additional context in comments.

3 Comments

@shaiwal Tripathi IN Dynamic SQL query for String Variable Closing Should be '''variable Name ''' Like this and Print The String_SQL to Check whether The query you Execute Is Proper or Not. it will you out in Solving Issue
if it's work's for you can vote And Accept The Answer
I'd immediately search for ';DROP TABLE DiagMain;--. Good luck.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.