December 14, 2009 at 12:11 pm
i know identity can be used with int
scenario
we need to code the page with PXXXX starting from P1000. every new insert should increment this value. the field is a char(5).
I am trying to avoid a trigger. are there any other options?
December 14, 2009 at 12:15 pm
You could use an integer column with the IDENTITY set on it and have it begin at 1000. Then create a computed column that takes the value 'P' and concatenates your IDENTITY column onto it. This would save you from having to lookup the MAX value of your column each time your want to insert.
December 14, 2009 at 12:17 pm
Two options...
1. Have two columns. One a Char(1) with default value of P and the other an Identity. When selecting Concat both fields. PK based on two fields.
2. Have a Char and take care of the updateed (New row) in the application layer.
Both are not good solutions.
-Roy
December 14, 2009 at 12:27 pm
here's a code example of what John and roy are talking about with the calculated column:
Create Table Example(P int identity(1000,1) , --starts at 1000
PCODE AS 'P' + CONVERT(varchar,(P)) PERSISTED, --gets calculated automatically,PERSISTED so it is stored in the table/faster access
SOMESTUFF VARCHAR(30) )
INSERT INTO Example(someStuff)
SELECT 'AUTO' UNION ALL
SELECT 'PCODE' UNION ALL
SELECT 'EXAMPLE'
SELECT * FROM Example
--results
P PCODE SOMESTUFF
1000 P1000 AUTO
1001 P1001 PCODE
1002 P1002 EXAMPLE
Lowell
December 14, 2009 at 1:51 pm
Thank you all. will try it out.
December 14, 2009 at 9:38 pm
John Rowan (12/14/2009)
You could use an integer column with the IDENTITY set on it and have it begin at 1000. Then create a computed column that takes the value 'P' and concatenates your IDENTITY column onto it. This would save you from having to lookup the MAX value of your column each time your want to insert.
It may also save the occasional deadlock and duplicate ID. Nicely done, John.
--Jeff Moden
Change is inevitable... Change for the better is not.
Viewing 6 posts - 1 through 5 (of 5 total)
You must be logged in to reply to this topic. Login to reply