joe (jc*****@hotmail.com) writes:
i just read an article on google that talked about using instead of
triggers so i was a little bet puzzled. but i got it to work
i bet it needs locking but here is the code
CREATE TABLE table1 (
pk int NOT NULL ,
flag int NULL
)
create function maxpk() returns int as
BEGIN
DECLARE @qty INT
SELECT @qty = 0
select @qty=max(pk)+1 from table1
return ISNULL(@qty, 0)
END
CREATE TRIGGER tr_test ON table1
INSTEAD OF INSERT
AS BEGIN
INSERT INTO table1(pk,flag)
select dbo.maxpk(), flag from inserted
END
Unfortunately, this won't fly well. It works if you insert one row at
a time, but as Adam pointed out, it fails for multi-row inserts. Also,
calling a user-defined function for each is bad for performance, because
the scalar UDF converts the statement to a cursor behind the scenes.
Again, this does not matter for a single-row insert, but if you insert
10000 rows, it will cost you dearly.
The simplest solution for this is to use - IDENTITY. But not on the
target table itself. Here's how you do it:
CREATE TABLE table1 (
pk int NOT NULL
CONSTRAINT default_pk DEFAULT 0,
flag int NULL,
CONSTRAINT pk_table1 PRIMARY KEY (pk)
)
go
CREATE TRIGGER tritest ON table1 INSTEAD OF INSERT AS
DECLARE @temp TABLE (ident int IDENTITY PRIMARY KEY,
flag int NULL)
DECLARE @maxpk int
INSERT @temp (flag)
SELECT flag FROM inserted
SELECT @maxpk = coalesce(MAX(pk), 0) FROM table1 WITH (UPDLOCK)
INSERT table1 (pk, flag)
SELECT @maxpk + ident, flag FROM @temp
go
INSERT table1 (flag)
SELECT OrderID FROM Northwind..Orders
go
SELECT * FROM table1
go
DROP TABLE table1
Of course, some people may ask why not use an IDENTITY column on
table1 directly? Well, assume that there is a business requirement
for a consecutive series of numbers, in which case IDENTITY won't do.
Then whether INSTEAD OF triggers is the way to go, I'm not really sure.
There is some extra maintenance job if you add more columns to the table.
--
Erland Sommarskog, SQL Server MVP,
es****@sommarskog.se
Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techinf...2000/books.asp