3

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

our.dom/red-sock

our.dom/red-sock-1

他们想要所有产品上的产品 ID 或其他数字,即

our.dom/red-sock-123481354

我将其存储在我称为 seourl 的字段中。

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

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

update tab set seourl=dbo.createurl(title)

肯定有碰撞,操作回滚。有没有办法让语句提交有效的更新,而其余的保持不变?

还是我必须在循环中执行 RBAR,Row By Agonizing Row 操作?

4

2 回答 2

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)
于 2013-06-11T12:17:44.107 回答
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()

于 2013-06-13T07:21:24.580 回答