比较 SQL Server 中的两个字符串 [英] comparing two strings in SQL Server

查看:43
本文介绍了比较 SQL Server 中的两个字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

int returnval = STRCMP(str1, str2)

  • 如果字符串相同则返回 0
  • 如果根据当前排序顺序第一个参数小于第二个参数,则返回 -1.
  • 否则返回 1.
  • 我在 MySQL 中找到了上述方法,但在 SQL Server 中找不到.

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

    推荐答案

    SQL Server中没有直接的字符串比较函数

    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
    

    注意事项

    • 您可以使用 CREATE FUNCTION 等通过 UDF 包装它
    • 您可能需要处理 NULL(在我上面的代码中,任何 NULL 都会报告 1)
    • str1 和 str2 将是列名或@variables

    这篇关于比较 SQL Server 中的两个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆