Click here to Skip to main content
15,884,472 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I want to auto generate if ticket_Code id like TS-2018-1
TS-2018-2
TS-2018-3

What I have tried:

CREATE TABLE [dbo].[Ticket] (
[Ticket_Code] INT IDENTITY (1, 1) NOT NULL,
CONSTRAINT [PK_Ticket] PRIMARY KEY CLUSTERED ([Ticket_Code] ASC)
);
Posted
Updated 30-Jan-18 2:39am
v2
Comments
CHill60 28-Jan-18 14:50pm    
You could use a trigger after insert to generate that from the identity column but these things are best done in the ui
Member 13646951 30-Jan-18 7:15am    
Ya Your are right .

This is the right way is sql , And Query Executed.
[S.No.] INT IDENTITY (1, 1) NOT NULL,
[Ticket_Code] AS ('TS-'+right('-2018-'+CONVERT([varchar](10),[S.No.],(0)),(6))) PERSISTED,

Worked !!!!!
 
Share this answer
 
v2
Comments
Jörgen Andersson 30-Jan-18 7:46am    
You could probably exchange 2018 for YEAR(SYSDATETIME())
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:
SQL
create table #ticket 
(
	[No] int identity(1,1),
	[year] int
)
insert into #ticket ([year]) values
(2017),(2017),(2018),(2018),(2018),(2019),(2019)

-- NB - and some more
insert into #ticket ([year]) values
(2017),(2017),(2018),(2018),(2018),(2019),(2019)
Note that the years do not appear in the "correct" order if you order just by the [No] column.

A query like this:
SQL
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)
SQL
;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
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900