尝试这个:
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()