比较SQL Server中的两个字符串

时间:2021-05-20 12:14:55

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

有没有办法比较SQL Server 2008存储过程中的两个字符串,如下所示?

int returnval = STRCMP(str1, str2)
  • returns 0 if the strings are the same
  • 如果字符串相同则返回0
  • returns -1 if the first argument is smaller than the second according to the current sort order.
  • 如果第一个参数根据当前排序顺序小于第二个参数,则返回-1。
  • returns 1 otherwise.
  • 否则返回1。

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

以上方法我在MySQL中找到但在SQL Server中找不到。

1 个解决方案

#1


28  

There is no direct string compare function in SQL Server

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
  • 你可以使用CREATE FUNCTION等通过UDF包装它
  • you may need NULL handling (in my code above, any NULL will report 1)
  • 你可能需要NULL处理(在我上面的代码中,任何NULL都会报告1)
  • str1 and str2 will be column names or @variables
  • str1和str2将是列名或@variables

#1


28  

There is no direct string compare function in SQL Server

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
  • 你可以使用CREATE FUNCTION等通过UDF包装它
  • you may need NULL handling (in my code above, any NULL will report 1)
  • 你可能需要NULL处理(在我上面的代码中,任何NULL都会报告1)
  • str1 and str2 will be column names or @variables
  • str1和str2将是列名或@variables