Witam
Mam problem z pobraniem wartości generowanej przez trigger typu "instead of insert" bezpośrednio po insercie rekordu.
Przykładowa tabela:
CREATE TABLE [dbo].[test1]
(
[id] [int] NOT NULL,
[id2] [int] NOT NULL,
[opis] [nchar](10) NULL,
CONSTRAINT [PK_test1] PRIMARY KEY CLUSTERED ([id] ASC, [id2] ASC)
)
w której pole id będące składową klucza głównego jest generowane przez trigger:
CREATE TRIGGER [dbo].[TR_TEST1] ON [dbo].[test1]
INSTEAD OF INSERT
AS
declare @id int;
declare @id2 int;
BEGIN
SET NOCOUNT ON;
SET @id = NULL;
select @id = id, @id2 = id2 from inserted;
if@id is null OR @id = 0
BEGIN
select @id = isnull(MAX(id),0) + 1 from [dbo].[test1] WHERE id2 = @id2;
select * INTO #inserted from inserted ;
declare _cursor CURSOR FOR select * from #inserted
for update
OPEN _cursor;
FETCH NEXT FROM _cursor
while @@FETCH_STATUS = 0
BEGIN
update #inserted set id = @id
where CURRENT OF _cursor;
SET @id = @id + 1;
FETCH NEXT FROM _cursor
END
CLOSE _cursor;
DEALLOCATE _cursor;
insert into [dbo].[test1] select * from #inserted;
END
ELSE
insert into [dbo].[test1](id, id2, opis) select * from inserted;
END
Założeniem jest aby pole id było generowane jako kolejny numer rekordu w obrębie identyfikatora id2 i aby można je było pobrać bezpośrednio z polecania insert.
przykład inserta z próbą wyciągnięcia wartości wygenerowanej przez triggera:
declare @tmp table(id1_tmpTable int, id2_tmpTable int)
insert into [dbo].test1(id2, opis) output inserted.id, inserted.id2 into @tmp VALUES(4, 'test');
select * from @tmp
Wartości zwracane z select * from @tmp to:
id1_tmpTable | id2_tmpTable |
---|---|
NULL | 3 |
Niestety zwracana wartość id jest nulowa |
I tutaj moja prośba, czy może spotkał się ktoś z podobnym problemem i wie jak go rozwiązać.
Od razu nadmienię, że nie ma możliwości dodania do tabeli dodatkowego pola z unikalnym identyfikatorem, po którym mógłbym później odpytać bazę o id z insertowanego rekordu.
Możliwe jest też oczywiście wyciągnięcie ostatniego id z zapytania:
select max(id) from dbo.test1 where id2 = @id2
Jednak jest to mało eleganckie rozwiązanie.