根据字段创建可读的唯一键

时间:2013-06-11 12:00:49

标签: sql-server-2008 rbar

webguys需要基于产品名称的唯一网址 如果更多产品具有相同名称,请在名称后面添加一个数字。

  

our.dom /红袜子

     

our.dom /红袜子-1

他们想要所有产品上的产品ID或其他号码,即

  

our.dom /红袜子123481354

我把它存放在一个我称之为seourl的字段中。

当我创建新产品时,我会覆盖它,触发器会尝试添加seourl,如果它已经存在,则递增数字,直到找到唯一值。

但我现在必须给整张桌子新的seourls。 如果我只是

update tab set seourl=dbo.createurl(title)

我肯定会发生碰撞,并且操作会被回滚。 有没有办法让语句提交有效的更新,并保持其余部分不变?

或者我必须只是做一个RBAR,在循环中按行Agonizing Row操作吗?

2 个答案:

答案 0 :(得分:0)

根据您的需要调整:

select
*
from (values('aaa'), ('aaa-12'), ('aaa-'), ('bbb-3')) as src (x)
cross apply (
    select isnull(nullif(patindex('%-[0-9]%', x) - 1, -1), LEN(x))
) as p(idx)
cross apply (
    select
        SUBSTRING(x, 1, idx)
        , SUBSTRING(x, idx + 1, LEN(x) - idx)
) as t(t, xx)

答案 1 :(得分:0)

试试这个:

declare @tmp table (
    id int not null identity
    , name varchar(100) -- you need name to be indexed
    , urlSuffix int -- store the number (ot you'll have to use PATINDEX, etc. as previously shown)!
    , url as name + ISNULL('_' + cast(NULLIF(urlSuffix, 0) as varchar(100)), '')

    , unique (name, id) -- (trick) index on name
)

insert @tmp (name, urlSuffix)
select
    src.name
    , ISNULL(T.urlSuffix, -1) + ROW_NUMBER() OVER (PARTITION BY src.name ORDER BY (select 1))
from (values
    ('x')
    , ('y')
    , ('y')
    , ('y')
    , ('z')
    , ('z')
) as src (name)
left join (
    select
        name
        , MAX(T.urlSuffix) as urlSuffix
    from @tmp AS T
    GROUP BY name
) as T on (
    T.name = src.name
)

insert @tmp (name, urlSuffix)
select
    src.name
    , ISNULL(T.urlSuffix, -1) + ROW_NUMBER() OVER (PARTITION BY src.name ORDER BY (select 1))
from (values
    ('a')
    , ('b')
    , ('b')
    , ('b')
    , ('z')
    , ('z')
) as src (name)
left join (
    select
        name
        , MAX(T.urlSuffix) as urlSuffix
    from @tmp AS T
    GROUP BY name
) as T on (
    T.name = src.name
)

select
    name, url
from @tmp
order by url

问题的解决方案应该在于使用ROW_NUMBER()