比较 SQL Server 中的两个字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6623802/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 11:16:06  来源:igfitidea点击:

comparing two strings in SQL Server

sqlsql-server-2008string-comparison

提问by Mahender

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
  • returns -1 if the first argument is smaller than the second according to the current sort order.
  • returns 1 otherwise.
  • 如果字符串相同则返回 0
  • 如果根据当前排序顺序第一个参数小于第二个参数,则返回 -1。
  • 否则返回 1。

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

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

回答by gbn

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