Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

comparing two strings in SQL Server

Is there any way to compare two strings in SQL Server 2008 stored procedure like below?

int returnval = STRCMP(str1, str2)
  • returns 0 if the strings are the same
  • returns -1 if the first argument is smaller than the second according to the current sort order.
  • returns 1 otherwise.

Above method I find in the MySQL but not in SQL Server.

like image 962
Mahender Avatar asked Jul 08 '11 11:07

Mahender


People also ask

Can I compare two strings in SQL?

In SQL Server, there are many built-in string functions that can be used by developers. We can compare strings by using the IF-ELSE statement.

Can you use == to compare two strings?

You should not use == (equality operator) to compare these strings because they compare the reference of the string, i.e. whether they are the same object or not. On the other hand, equals() method compares whether the value of the strings is equal, and not the object itself.

How do I compare two columns of strings in SQL?

We can compare two or more strings using the STRCMP string function, LIKE operator, and Equal operator.

How do you compare 2 strings?

String strcmp() function in C++ In order to compare two strings, we can use String's strcmp() function. The strcmp() function is a C library function used to compare two strings in a lexicographical manner. The function returns 0 if both the strings are equal or the same.


1 Answers

There is no direct string compare function in SQL Server

CASE
  WHEN str1 = str2 THEN 0
  WHEN str1 < str2 THEN -1
  WHEN str1 > str2 THEN 1
  ELSE NULL --one of the strings is NULL so won't compare (added on edit)
END

Notes

  • you can wraps this via a UDF using CREATE FUNCTION etc
  • you may need NULL handling (in my code above, any NULL will report 1)
  • str1 and str2 will be column names or @variables
like image 114
gbn Avatar answered Sep 19 '22 09:09

gbn