【问题标题】:SQL-'08: Are multiple Replace statements a bad practice/is there another way to write this query?SQL-'08:多个 Replace 语句是一种不好的做法/是否有另一种方法来编写此查询?
【发布时间】:2011-07-25 10:18:11
【问题描述】:
Select 
Distinct 
    REPLACE(REPLACE(REPLACE(REPLACE(Category, ' & ', '-'), '/', '-'), ', ', '-'), ' ', '-') AS Department 
From 
     Inv WITH(NOLOCK) 

我想知道,因为我是一名 Jr. ETL 工程师,想养成良好的习惯。

显然,在许多情况下,这可能会变得更长。

【问题讨论】:

  • 我正在使用您的代码变体来尝试在 MS Access 表中进行多次替换。它运行(没有弹出错误消息),但是在我的替换字段中(与您的“部门”匹配的那个,我得到#Error返回。知道为什么吗?很可能我应该将其作为一个单独的问题发布.

标签: sql sql-server-2008 ssis replace


【解决方案1】:

使用 SQLCLR 和正则表达式可能会更好。 http://blogs.msdn.com/b/sqlclr/archive/2005/06/29/regex.aspx

当然,这可以更易于维护和灵活。

就性能而言,您通常会发现很难超越内置函数,但对于许多 REPLACE 操作,CLR 可能会胜过它 - 您必须进行基准测试。

我注意到您说您在 SSIS 中执行此操作 - 在这种情况下,您可以在数据流中使用各种其他可能的方法,包括脚本任务和正则表达式。作为一般规则,您需要评估您正在执行的每个操作并决定是否应该在将数据带入数据流的查询中或在数据流本身中完成它。某些操作(如过滤)可以更好地在源上执行,但其他操作(如聚合)可能更好地在数据流中完成,特别是如果它们对任何类型的运行数据都是有状态的。

【讨论】:

    【解决方案2】:

    嵌套替换很好,但是随着嵌套级别的增加,代码的可读性会下降。如果我要替换大量字符,我会选择更简洁的方法,例如下表驱动的方法。

        declare @Category varchar(25)
        set @Category = 'ABC & DEF/GHI, LMN OP'
        -- nested replace
        select replace(replace(replace(replace(@Category, ' & ', '-'), '/', '-'), ', ', '-'), ' ', '-') as Department 
    
        -- table driven
        declare @t table (ReplaceThis varchar(10), WithThis varchar(10))
        insert into @t
            values  (' & ', '-'), 
                    ('/', '-'),
                    (', ', '-'),
                    (' ', '-')
    
        select  @Category = replace(@Category, ReplaceThis, isnull(WithThis, ''))                       
        from    @t
        where   charindex(ReplaceThis, @Category) > 0;
    
        select @Category [Department]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-28
      相关资源
      最近更新 更多