Search code examples
sqlsql-servert-sqlsql-like

LIKE operator, N and % SQL Server doesn't work on nvarchar column


Is there any way to make following query Work?

declare @t nvarchar(20)
set @t='حس'
SELECT  [perno] ,[pName]
  FROM  [dbo].[People]
  Where [pName] like N''+@t +'%'

I cann't use like this:

 Where [pName] like N'حس%'

Or using an stored procedure :

  ALTER PROCEDURE [dbo].[aTest]
  (@t  nvarchar(20))
  AS
    BEGIN

     SELECT     [perno] ,[pName]
       FROM     [dbo].[People]
       WHERE   ([People].[pName] LIKE N'' +@t + '%')
END   

Solution

  • You don't need to use N prefix in the WHERE clause since your variable is already nvarchar, and you are passing a variable not a literal string.

    Here is an example:

    CREATE TABLE People
    (
      ID INT,
      Name NVARCHAR(45)
    );
    
    INSERT INTO People VALUES
    (1, N'حسام'),
    (2, N'حسان'),
    (3, N'حليم');
    
    DECLARE @Name NVARCHAR(45) = N'حس';--You need to use N prefix when you pass the string literal
    
    SELECT *
    FROM People
    WHERE Name LIKE @Name + '%'; --You can use it here when you pass string literal, but since you are passing a variable, you don't need N here
    

    Live demo

    You may have seen Transact-SQL code that passes strings around using an N prefix. This denotes that the subsequent string is in Unicode (the N actually stands for National language character set). Which means that you are passing an NCHAR, NVARCHAR or NTEXT value, as opposed to CHAR, VARCHAR or TEXT.

    From docs

    Prefix Unicode character string constants with the letter N. Without the N prefix, the string is converted to the default code page of the database. This default code page may not recognize certain characters.


    To answer your question in the comment with a simple answer, you are using the wrong datatype, so ALTER the stored procedure and change the datatype of your parameter from VARCHAR to NVARCHAR.


    UPDATE:

    Since you are using an SP, you can create your SP (according to your comment) as

    CREATE PROCEDURE MyProc
    (
      @Var NVARCHAR(45)
    )
    AS 
    BEGIN
      SELECT *
      FROM People
      WHERE Name LIKE ISNULL(@Var, Name) + '%';
      --Using ISNULL() will return all rows if you pass NULL to the stored procedure
    END
    

    and call it as

    EXEC MyProc N'حس'; --If you don't use N prefix then you are pass a varchar string
    

    If you see, you need to use the N prefix when you pass literal string to your SP not inside the SP or the WHERE clause neither.

    Demo for the SP