comparing two strings in SQL Server

2020-06-08 12:45发布

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.

1条回答
对你真心纯属浪费
2楼-- · 2020-06-08 13:44

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
查看更多
登录 后发表回答