Solved

autonumber with a variable prefix

Posted on 2006-06-22
3
549 Views
Last Modified: 2009-12-16
folks

I have an autonumber eg BTU 1001

when I hit insert it has to be BTU1002

though the prefix BTU can be different

so I might have

CTU 233

the next would be CTU234

how can I build a trigger

so when I insert a new record i.e with the prefix

BTU and then save it it will take the last number and add one eg

BTU1003  (BTU1002+1)

when I then put in

CTU and save then CTU235 will crop up

all help will do

rutger



0
Comment
Question by:rutgermons
3 Comments
 
LVL 6

Expert Comment

by:davbouchard
ID: 16962343
Create a table that has 2 columns  Prefix (char(xx)) and NextNumber (int)

Inside the trigger

1. look up the NextNumber for that prefix
2. Grab it
3. Update that record with the next number

If the Prefix isn't found, insert it and start at 1 or whatever number you want.

0
 

Author Comment

by:rutgermons
ID: 16962363
could u assist with an example pls?

r
0
 
LVL 28

Accepted Solution

by:
imran_fast earned 500 total points
ID: 16974848
SOMETHING LIKE THS




CREATE TRIGGER [TRIGGER NAME] ON [dbo].[test]
instead of  INSERT
AS
BEGIN
      DECLARE @COLUMN VARCHAR(10)
      
      SELECT @COLUMN = COL FROM INSERTED
      INSERT INTO  TEST (COL)
      SELECT @COLUMN +  CAST (ISNULL(MAX(CAST(REPLACE(COL,@COLUMN ,'') AS INT) +1),0) AS VARCHAR(10))  FROM TEST WHERE COL LIKE '%'+@COLUMN+'%'
END
GO
INSERT INTO TEST VALUES('CTU')
0

Featured Post

Use Case: Protecting a Hybrid Cloud Infrastructure

Microsoft Azure is rapidly becoming the norm in dynamic IT environments. This document describes the challenges that organizations face when protecting data in a hybrid cloud IT environment and presents a use case to demonstrate how Acronis Backup protects all data.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Let's review the features of new SQL Server 2012 (Denali CTP3). It listed as below: PERCENT_RANK(): PERCENT_RANK() function will returns the percentage value of rank of the values among its group. PERCENT_RANK() function value always in be…
Ever wondered why sometimes your SQL Server is slow or unresponsive with connections spiking up but by the time you go in, all is well? The following article will show you how to install and configure a SQL job that will send you email alerts includ…
Via a live example, show how to set up a backup for SQL Server using a Maintenance Plan and how to schedule the job into SQL Server Agent.
Via a live example, show how to shrink a transaction log file down to a reasonable size.

830 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question