【问题标题】:SQL Server : distinct with trailing whitespaceSQL Server:与尾随空格不同
【发布时间】:2016-07-10 02:52:17
【问题描述】:

如何让这个示例显示 ('space') 和 ('space')?

create table #example
( 
    myString varchar(50)
)

insert into #example values ('space'), ('space ')

select distinct * 
from #example

我知道 SQL 比较运算符认为这两个字符串是等价的,但我不适合这种情况。

https://support.microsoft.com/en-us/kb/316626

SQL WHERE clause matching values with trailing spaces

跟进回答

注意:DATALENGTH(...) 函数也可以产生一个对尾随空格敏感的连接:

select *
from table1
left join table2 on table1.id1 = table2.id1 
                 and datalength(table1.id1) = datalength(table2.id1)

【问题讨论】:

    标签: sql-server


    【解决方案1】:

    试试这个:

    SELECT A.myString
    FROM (
        SELECT DISTINCT myString, DATALENGTH(myString) [DataLength]
        FROM #example
        ) A
    

    有了这些数据:

    insert into #example values ('space'),
    ('space '),
    ('space2'),
    ('space2');
    

    结果:

    myString
    --------
    space
    space 
    space2
    

    【讨论】:

    • 我一起破解了一些东西,添加然后删除了一个额外的字符,但这更优雅。谢谢。
    【解决方案2】:

    您可以通过删除 select stmt 中的 distinct 关键字来实现...

    从 #example 中选择 myString

    从#example中选择*

    但我想这个问题不仅仅是这个......?

    编辑:

    select  myString  
    --, rtrim(myString)  as newstring -- uncomment for troubleshooting
    from #example
    WHERE rtrim(myString)  not like '% %'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-02
      • 1970-01-01
      • 2015-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-29
      • 1970-01-01
      相关资源
      最近更新 更多