Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

sp_executesql Not Working with a Parameters search nvarchar

I try to make my problem to sample.
Some thing like this

CREATE TABLE test(
    [No] [bigint] IDENTITY(1,1) PRIMARY key,
    [Title] [nvarchar](100) NOT NULL
) 
GO

insert into test(Title)
select '개인경비 청구서 작성 및 교육'
union all 
select 'a'
    
create PROCEDURE [dbo].[Notice_Dels]            
    @SerchText  NVARCHAR(200)

AS BEGIN
   DECLARE @Query NVARCHAR(MAX);
    SET @Query  =  N'select
             N.No, 
             N.Title
        FROM test  N 
        WHERE 
         N.Title 
        LIKE N''%@SerchText%''   '
    PRINT @Query
    EXEC SP_EXECUTESQL @Query, N' @SerchText   NVARCHAR(200)', @SerchText   
END

exec [Notice_Dels] N'개인경비';

It give me no row. How can I fix it?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You are correctly attempting to debug your dynamic SQL by using the PRINT statement, but you don’t appear to have checked that the SQL it produces is correct. Because this:

SELECT
    N.No, 
    N.Title
FROM test N 
WHERE N.Title LIKE N'%@SerchText%'   

Is searching for text containing the string '@SerchText' not the contents of the variable @SerchText.
You need to change the LIKE line as follows – see how we are now concatenating the contents of @SerchText:

LIKE N''%'' + @SerchText + ''%''   '

This now produces the following SQL which I believe is what you require:

SELECT
    N.No, 
    N.Title
FROM test N 
WHERE N.Title LIKE N'%' + @SerchText + '%'  

Note your example data also has an issue, but I assume your actual data does not. You are inserting non-Unicode data in your example (which also doesn’t work) e.g.

SELECT '개인경비 청구서 작성 및 교육'

whereas you should be inserting Unicode data e.g.

SELECT N'개인경비 청구서 작성 및 교육'

DBFiddle

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading