As Jörgen Andersson has pointed out, you probably want to replace the hard-coded '2018' with a year extracted from something. It also looks as if you might want to start the renumbering for each year.
Something like this works (BUT does assume that no records will be deleted)..
I created and populated a temp table for the demo thus:
create table #ticket
(
[No] int identity(1,1),
[year] int
)
insert into #ticket ([year]) values
(2017),(2017),(2018),(2018),(2018),(2019),(2019)
insert into #ticket ([year]) values
(2017),(2017),(2018),(2018),(2018),(2019),(2019)
Note that the
year
s do not appear in the "correct" order if you order just by the
[No]
column.
A query like this:
select [No], [Year], 'TS-' + cast([year] as char(4)) + '-' + CAST(ROW_NUMBER() OVER (PARTITION BY [year] ORDER BY [No]) as varchar)
from #ticket order by [year], [No]
gave me these results:
1 2017 TS-2017-1
2 2017 TS-2017-2
8 2017 TS-2017-3
9 2017 TS-2017-4
3 2018 TS-2018-1
4 2018 TS-2018-2
5 2018 TS-2018-3
10 2018 TS-2018-4
11 2018 TS-2018-5
12 2018 TS-2018-6
6 2019 TS-2019-1
7 2019 TS-2019-2
13 2019 TS-2019-3
14 2019 TS-2019-4
or the slightly nicer (in my opinion)
;with c as (
select [No], [Year],
ROW_NUMBER() OVER (PARTITION BY [year] ORDER BY [No]) as yno from #ticket
)
select [No], [Year], Format([Year], 'TS-####') + Format(yno, '-####') from c
But as I said earlier, often this sort of manipulation (formatting text and numbers) is best left to the UI layer