473,753 Members | 8,077 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Using a trigger to generate an ID value

The table in the database has a field called LabID. That field is an
integer and consists of the year plus a counter. For example, the
first record of 2006 would be "20060001," the second record of 2006
would be "20060002" and so on. I'm trying to create an Insert trigger
that can generate the ID value when a new record is inserted, but I'm
not quite sure how to implement that trigger. Can anyone help?

Sep 15 '06 #1
11 6038
im************* ******@yahoo.co m (im************ *******@yahoo.c om) writes:
The table in the database has a field called LabID. That field is an
integer and consists of the year plus a counter. For example, the
first record of 2006 would be "20060001," the second record of 2006
would be "20060002" and so on. I'm trying to create an Insert trigger
that can generate the ID value when a new record is inserted, but I'm
not quite sure how to implement that trigger. Can anyone help?
The script below demonstrates. Note that it presumes that the table
already has an identifyable key, else there is no possibility to handle
multi-row inserts.

The solution presumes SQL 2005.

CREATE TABLE nisse (a int NOT NULL PRIMARY KEY,
LabID int NULL)
CREATE INDEX LabID_ix ON nisse(LabID)
go
CREATE TRIGGER nisse_tri ON nisse FOR INSERT AS
DECLARE @curmax int,
@curyear int,
@rowc int

SELECT @rowc = @@rowcount
IF @rowc = 0
RETURN

SELECT @curyear = year(getdate()) * 10000

SELECT @curmax = coalesce(MAX(La bID) - @curyear, 0)
FROM nisse (HOLDLOCK)
WHERE LabID BETWEEN @curyear + 1 AND @curyear + 9999

IF @curmax + @rowc 10000
BEGIN
ROLLBACK TRANSACTION
RAISERROR ('%d rows have already been inserted this year, so you cannot
insert %d rows now. Please wait until next year',
16, 1, @curmax, @rowc)
RETURN
END

UPDATE nisse
SET LabID = @curyear + @curmax + i.newlabid
FROM nisse n
JOIN (SELECT a, newlabid = row_number() over (ORDER BY a)
FROM inserted) AS i ON n.a = i.a
go
INSERT nisse (a)
SELECT 8
UNION ALL SELECT 188
UNION ALL SELECT 234
go
select * from nisse
INSERT nisse (a)
SELECT 18
UNION ALL SELECT 5188
UNION ALL SELECT 9234
go
select * from nisse
drop table nisse
--
Erland Sommarskog, SQL Server MVP, es****@sommarsk og.se

Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pro...ads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodinf...ons/books.mspx
Sep 16 '06 #2
Thank you for the response. Please bear in mind that the LabID is the
identifiable key; it is the PK for the table. Also, I don't understand
why LabID = @curyear + @curmax + i.newlabid instead of @curyear +
(@curmax + 1). Finally, could you please explain to me why the UNION
statements are necessary?

Again, thank you very much.
Erland Sommarskog wrote:
im************* ******@yahoo.co m (im************ *******@yahoo.c om) writes:
The table in the database has a field called LabID. That field is an
integer and consists of the year plus a counter. For example, the
first record of 2006 would be "20060001," the second record of 2006
would be "20060002" and so on. I'm trying to create an Insert trigger
that can generate the ID value when a new record is inserted, but I'm
not quite sure how to implement that trigger. Can anyone help?

The script below demonstrates. Note that it presumes that the table
already has an identifyable key, else there is no possibility to handle
multi-row inserts.

The solution presumes SQL 2005.

CREATE TABLE nisse (a int NOT NULL PRIMARY KEY,
LabID int NULL)
CREATE INDEX LabID_ix ON nisse(LabID)
go
CREATE TRIGGER nisse_tri ON nisse FOR INSERT AS
DECLARE @curmax int,
@curyear int,
@rowc int

SELECT @rowc = @@rowcount
IF @rowc = 0
RETURN

SELECT @curyear = year(getdate()) * 10000

SELECT @curmax = coalesce(MAX(La bID) - @curyear, 0)
FROM nisse (HOLDLOCK)
WHERE LabID BETWEEN @curyear + 1 AND @curyear + 9999

IF @curmax + @rowc 10000
BEGIN
ROLLBACK TRANSACTION
RAISERROR ('%d rows have already been inserted this year, so you cannot
insert %d rows now. Please wait until next year',
16, 1, @curmax, @rowc)
RETURN
END

UPDATE nisse
SET LabID = @curyear + @curmax + i.newlabid
FROM nisse n
JOIN (SELECT a, newlabid = row_number() over (ORDER BY a)
FROM inserted) AS i ON n.a = i.a
go
INSERT nisse (a)
SELECT 8
UNION ALL SELECT 188
UNION ALL SELECT 234
go
select * from nisse
INSERT nisse (a)
SELECT 18
UNION ALL SELECT 5188
UNION ALL SELECT 9234
go
select * from nisse
drop table nisse
--
Erland Sommarskog, SQL Server MVP, es****@sommarsk og.se

Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pro...ads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodinf...ons/books.mspx
Sep 18 '06 #3
Thank you for the response. Please bear in mind that the LabID is the
identifiable key; it is the PK for the table. Also, I don't understand

why LabID = @curyear + @curmax + i.newlabid instead of @curyear +
(@curmax + 1). Finally, could you please explain to me why the UNION
statements are necessary?

Again, thank you very much.
im************* ******@yahoo.co m wrote:
Thank you for the response. Please bear in mind that the LabID is the
identifiable key; it is the PK for the table. Also, I don't understand
why LabID = @curyear + @curmax + i.newlabid instead of @curyear +
(@curmax + 1). Finally, could you please explain to me why the UNION
statements are necessary?

Again, thank you very much.
Erland Sommarskog wrote:
im************* ******@yahoo.co m (im************ *******@yahoo.c om) writes:
The table in the database has a field called LabID. That field is an
integer and consists of the year plus a counter. For example, the
first record of 2006 would be "20060001," the second record of 2006
would be "20060002" and so on. I'm trying to create an Insert trigger
that can generate the ID value when a new record is inserted, but I'm
not quite sure how to implement that trigger. Can anyone help?
The script below demonstrates. Note that it presumes that the table
already has an identifyable key, else there is no possibility to handle
multi-row inserts.

The solution presumes SQL 2005.

CREATE TABLE nisse (a int NOT NULL PRIMARY KEY,
LabID int NULL)
CREATE INDEX LabID_ix ON nisse(LabID)
go
CREATE TRIGGER nisse_tri ON nisse FOR INSERT AS
DECLARE @curmax int,
@curyear int,
@rowc int

SELECT @rowc = @@rowcount
IF @rowc = 0
RETURN

SELECT @curyear = year(getdate()) * 10000

SELECT @curmax = coalesce(MAX(La bID) - @curyear, 0)
FROM nisse (HOLDLOCK)
WHERE LabID BETWEEN @curyear + 1 AND @curyear + 9999

IF @curmax + @rowc 10000
BEGIN
ROLLBACK TRANSACTION
RAISERROR ('%d rows have already been inserted this year, so you cannot
insert %d rows now. Please wait until next year',
16, 1, @curmax, @rowc)
RETURN
END

UPDATE nisse
SET LabID = @curyear + @curmax + i.newlabid
FROM nisse n
JOIN (SELECT a, newlabid = row_number() over (ORDER BY a)
FROM inserted) AS i ON n.a = i.a
go
INSERT nisse (a)
SELECT 8
UNION ALL SELECT 188
UNION ALL SELECT 234
go
select * from nisse
INSERT nisse (a)
SELECT 18
UNION ALL SELECT 5188
UNION ALL SELECT 9234
go
select * from nisse
drop table nisse
--
Erland Sommarskog, SQL Server MVP, es****@sommarsk og.se

Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pro...ads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodinf...ons/books.mspx
Sep 18 '06 #4
im************* ******@yahoo.co m (im************ *******@yahoo.c om) writes:
Thank you for the response. Please bear in mind that the LabID is the
identifiable key; it is the PK for the table.
In such case you cannot use an AFTER trigger. A primary key cannot be NULL,
so it must have a value when you insert the data. Furthermore, if there is
no other data to correlate, it's impossible to handle multi-row inserts.
And a trigger that would reqiure rows to be inserted one at a time, is
completely indefensible. This could have serious impact the day you
need to insert many rows.
Also, I don't understand why LabID = @curyear + @curmax + i.newlabid
instead of @curyear + (@curmax + 1).
If you insert 10 rows at the time, you cannot give them all the same
ID, can you?
Finally, could you please explain to me why the UNION statements are
necessary?
I wanted to test that the trigger actually works with multi-row inserts.
SELECT UNION is a way to achieve that without using a table to select
from.

I think it's possible to do this with INSTEAD OF trigger, but then I
need to know which version of SQL Server you are using.
--
Erland Sommarskog, SQL Server MVP, es****@sommarsk og.se

Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pro...ads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodinf...ons/books.mspx
Sep 18 '06 #5
I'm using SQL Server 2005. By the way, the front-end app is an Access
Data Project.

Erland Sommarskog wrote:
im************* ******@yahoo.co m (im************ *******@yahoo.c om) writes:
Thank you for the response. Please bear in mind that the LabID is the
identifiable key; it is the PK for the table.

In such case you cannot use an AFTER trigger. A primary key cannot be NULL,
so it must have a value when you insert the data. Furthermore, if there is
no other data to correlate, it's impossible to handle multi-row inserts.
And a trigger that would reqiure rows to be inserted one at a time, is
completely indefensible. This could have serious impact the day you
need to insert many rows.
Also, I don't understand why LabID = @curyear + @curmax + i.newlabid
instead of @curyear + (@curmax + 1).

If you insert 10 rows at the time, you cannot give them all the same
ID, can you?
Finally, could you please explain to me why the UNION statements are
necessary?

I wanted to test that the trigger actually works with multi-row inserts.
SELECT UNION is a way to achieve that without using a table to select
from.

I think it's possible to do this with INSTEAD OF trigger, but then I
need to know which version of SQL Server you are using.
--
Erland Sommarskog, SQL Server MVP, es****@sommarsk og.se

Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pro...ads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodinf...ons/books.mspx
Sep 18 '06 #6
im************* ******@yahoo.co m (im************ *******@yahoo.c om) writes:
I'm using SQL Server 2005. By the way, the front-end app is an Access
Data Project.
Ok, here is a revised and tested version using an INSTEAD OF trigger:

CREATE TABLE nisse (LabID int NOT NULL PRIMARY KEY,
somemoredata int NULL)
go
CREATE TRIGGER nisse_tri ON nisse INSTEAD OF INSERT AS
DECLARE @curmax int,
@curyear int,
@rowc int

SELECT @rowc = @@rowcount
IF @rowc = 0
RETURN

SELECT @curyear = year(getdate()) * 10000

SELECT @curmax = coalesce(MAX(La bID) - @curyear, 0)
FROM nisse (HOLDLOCK)
WHERE LabID BETWEEN @curyear + 1 AND @curyear + 9999

IF @curmax + @rowc 10000
BEGIN
ROLLBACK TRANSACTION
RAISERROR ('%d rows have already been inserted this year, so you cannot insert %d rows now. Please wait until next year',
16, 1, @curmax, @rowc)
RETURN
END

INSERT nisse(LabID, somemoredata)
SELECT @curyear + @curmax + row_number() OVER (ORDER BY newid()),
somemoredata
FROM inserted
go
INSERT nisse (somemoredata)
SELECT 8
UNION ALL SELECT 188
UNION ALL SELECT 234
go
select * from nisse
INSERT nisse (somemoredata)
SELECT 18
UNION ALL SELECT 5188
UNION ALL SELECT 9234
go
select * from nisse
drop table nisse
--
Erland Sommarskog, SQL Server MVP, es****@sommarsk og.se

Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pro...ads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodinf...ons/books.mspx
Sep 19 '06 #7
BLESS YOU!!! I'll look at this immediately.

Erland Sommarskog wrote:
im************* ******@yahoo.co m (im************ *******@yahoo.c om) writes:
I'm using SQL Server 2005. By the way, the front-end app is an Access
Data Project.

Ok, here is a revised and tested version using an INSTEAD OF trigger:

CREATE TABLE nisse (LabID int NOT NULL PRIMARY KEY,
somemoredata int NULL)
go
CREATE TRIGGER nisse_tri ON nisse INSTEAD OF INSERT AS
DECLARE @curmax int,
@curyear int,
@rowc int

SELECT @rowc = @@rowcount
IF @rowc = 0
RETURN

SELECT @curyear = year(getdate()) * 10000

SELECT @curmax = coalesce(MAX(La bID) - @curyear, 0)
FROM nisse (HOLDLOCK)
WHERE LabID BETWEEN @curyear + 1 AND @curyear + 9999

IF @curmax + @rowc 10000
BEGIN
ROLLBACK TRANSACTION
RAISERROR ('%d rows have already been inserted this year, so you cannot insert %d rows now. Please wait until next year',
16, 1, @curmax, @rowc)
RETURN
END

INSERT nisse(LabID, somemoredata)
SELECT @curyear + @curmax + row_number() OVER (ORDER BY newid()),
somemoredata
FROM inserted
go
INSERT nisse (somemoredata)
SELECT 8
UNION ALL SELECT 188
UNION ALL SELECT 234
go
select * from nisse
INSERT nisse (somemoredata)
SELECT 18
UNION ALL SELECT 5188
UNION ALL SELECT 9234
go
select * from nisse
drop table nisse
--
Erland Sommarskog, SQL Server MVP, es****@sommarsk og.se

Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pro...ads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodinf...ons/books.mspx
Sep 21 '06 #8
Again, thank you very much. Am I right to assume that the following
section is unnecessary, just for testing?
INSERT nisse (somemoredata)
SELECT 8
UNION ALL SELECT 188
UNION ALL SELECT 234
go
select * from nisse
INSERT nisse (somemoredata)
SELECT 18
UNION ALL SELECT 5188
UNION ALL SELECT 9234
go
select * from nisse
drop table nisse
Sep 21 '06 #9
im************* ******@yahoo.co m (im************ *******@yahoo.c om) writes:
Again, thank you very much. Am I right to assume that the following
section is unnecessary, just for testing?
>INSERT nisse (somemoredata)
SELECT 8
UNION ALL SELECT 188
UNION ALL SELECT 234
go
select * from nisse
INSERT nisse (somemoredata)
SELECT 18
UNION ALL SELECT 5188
UNION ALL SELECT 9234
go
select * from nisse
drop table nisse
Well, testing is never unnecessary. :-)

But you are right that this is not part of the solution.
--
Erland Sommarskog, SQL Server MVP, es****@sommarsk og.se

Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pro...ads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodinf...ons/books.mspx
Sep 21 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
4580
by: June Moore | last post by:
Hi all, I have two tables tbl_A and tbl_B. Table Definitions: tbl_A (field_1, field_2, field_3) tbl_B (field_1, field_2) I would like to populate tbl_B when a record is inserted into tbl_A. Note that tbl_A.field_1 = tbl_B.field_1 and tbl_A.field_2 = tbl_B.field_2 . How do I write a trigger on tbl_A to get the corresponding record
4
3450
by: Pat Turner | last post by:
Hi, I have some XML like this: <family> <person name="bob"> <father ref="../../person" /> </person> <person name="charlie"> <child ref="../../person" />
5
5377
by: Jason | last post by:
Hi all basically its what i said in the subject. Would just like to know how to split a string using a STRING value as the delimeter and not a CHAR as the delimeter. Example: "I like Cheese", how would i get the following array: strArray = "I"; strArray = "Cheese", using "like" as the delimeter Thanks! Jason
3
4204
by: Jason Huang | last post by:
Hi, MyForm is a C# Windows Form. MyFom has 3 GroupBoxes. Now I wanna update data from the textboxes in those 3 GroupBoxes. I have function Update1 for GroupBox1 to update table Table1, Update2 for GroupBox2 to update table Table2, Update3 for GroupBox3 to update table Table3. And there is a function TotalUpdate for MyForm. The function TotalUpdate comprises of Update1, Update2, and Update3.
1
8350
by: lytung | last post by:
Hi all, i am having trouble trying to export this in xml. Basically inside an update trigger i need to export in xml or file the qty that has been changed. This then gets updated to another system. Is this a good idea ? should i be using another table in between in case something happens on the other end? However, I tried something like this and it didn't recognize the selected table inside the bcp:
1
1880
by: gaurkamal | last post by:
I want to delete record in table B when i delete record in Table A both table have a common column. I want to do it using trigger .Can any body give some idea. Table details are. Table A: Channel_ID, Name Table B User_Id,Channel_ID, Description
4
2565
by: simo | last post by:
I have a requirement to create a sorted list of objects, stored within an assembly, and I would like to use a After Insert/Update trigger to notify that assembly that something has changed, rather than polling the database for changes all the time. My initial problem is that I need to create a static list so that it can be dynamically looked at by other assemblies, but SQL Server won't allow me to attach a dll which contains a static...
7
5724
by: John Smith | last post by:
Hello, I have a simple question, I have a vb.net form with several buttons. If I store the name of a button in a variable.. Dim TheName as string TheName = Me.btnMyLittleButton.Name.ToString How can I disable this button using the variable value?
2
1737
by: potti | last post by:
Hi, I am inserting data in table1.using a trigger I want to populate TABLE2.My code is like this : TABLE1 :ST_INFO FIELDS : NAME (varchar),ACCOUNT_TYPE(varchar),TIME(date) TABLE2 :TOTALS FIELDS : CURR_DAY(date),DISCONNECTIONS(number) I am inserting data in ST_INFO using SQLLOADER.I want to populate TOTALS with the TIME,count of TIME field after insertion. CREATE OR REPLACE TRIGGER TRI_TOTALS AFTER INSERT ON ST_INFO FOR EACH ROW BEGIN
0
865
by: Gabriel Genellina | last post by:
En Tue, 14 Oct 2008 18:08:53 -0300, Joe Python <jopython@gmail.com> escribió: The pattern must match the *separator* only. Try with: pattern = r'\d+/\d+/\d+ \d+:\d+:\d+ (AM|PM)' -- Gabriel Genellina
0
9072
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8896
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9653
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9451
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9421
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9333
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8328
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6869
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
1
3395
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.