Babak.Abad
Babak.Abad

Reputation: 2956

Comparing strings in SQL Server

I'm programming in C# (WPF) and SQL Server 2012 Enterprise. My program is an auto answering machine so I should compare incoming message with an existing keyword in the database.

In my application (in a database function), I compare two strings which both of them are come from Persian language. One of them is stored in database and the other comes from a web service method. When I compare two string which are similar together, result shows that they are different!

For example I save keyword خرید in my database and incoming message is خرید too. But comparison shows they are different!

I also try two compare them in c# and I also use CultureInfo but still I have problem.

How can I solve this problem?

Upvotes: 2

Views: 740

Answers (2)

M.Ali
M.Ali

Reputation: 69514

You need to make sure when you are storing the value in a sql variable you use NVARCHAR datatype for the variable and when Assigning the value to variable use N prefix with your strings to tell sql server that there will be unicode characters in the string . Try the following to see your self.

DECLARE @Nvar1 NVARCHAR = N'خرید'
DECLARE @Nvar2 NVARCHAR = N'خرید'

IF (@Nvar1 = @Nvar2)
 BEGIN
   PRINT 'Test 1'
   PRINT 'Strings Are Equal'
 END 
ELSE
 BEGIN
   PRINT 'Test 1'
   PRINT 'Strings Are Not Equal'
 END

Test 1
Strings Are Equal


DECLARE @Nvar3 NVARCHAR = N'ی'
DECLARE @Nvar4 NVARCHAR = N'ي'

IF (@Nvar3 = @Nvar4)
 BEGIN
   PRINT 'Test 2'
   PRINT 'Strings Are Equal'
 END 
ELSE
 BEGIN
   PRINT 'Test 2'
   PRINT 'Strings Are Not Equal'
 END

Test 2
Strings Are Not Equal

Upvotes: 1

Amir Keshavarz
Amir Keshavarz

Reputation: 3108

That is beacuse of 'ی' , one of them are 'ي' and the other is 'ی' . You can replace one with other. so inside your inserts use replace function to replace all 'ي' with 'ی' . it is gonna be ok now.

Upvotes: 0

Related Questions