我有一个而不是触发器来插入,删除和更新我的视图。 我在插入两行或更多行时遇到了一些问题。
IF EXISTS(SELECT * FROM inserted) AND NOT EXISTS(SELECT * FROM deleted)
BEGIN
DECLARE @LastId INT
INSERT INTO Sales.CreditCard
SELECT
i.CardType,
i.CardNumber,
i.ExpMonth,
i.ExpYear,
GETDATE()
FROM inserted i
SELECT @LastId = @@IDENTITY
INSERT INTO Sales.PersonCreditCard
(BusinessEntityID,
CreditCardID,
ModifiedDate)
SELECT
i.BusinessEntityID,
@LastId,
GETDATE()
FROM inserted i
END
SELECT @LastId = @@IDENTITY
获取最后一行的ID
,但我插入两个或更多。如何更改此脚本以插入两行以上的行?
答案 0 :(得分:0)
我认为我解决了我的问题,但我不确定这是一个很好的解决方案。你觉得怎么样?
IF EXISTS(SELECT * FROM inserted) AND NOT EXISTS(SELECT * FROM deleted)
BEGIN
DECLARE @LastId TABLE (ID INT, Number NVARCHAR(25))
INSERT INTO Sales.CreditCard
OUTPUT inserted.CreditCardID, inserted.CardNumber INTO @LastId
SELECT
i.CardType,
i.CardNumber,
i.ExpMonth,
i.ExpYear,
GETDATE()
FROM inserted i
INSERT INTO Sales.PersonCreditCard
(BusinessEntityID,
CreditCardID,
ModifiedDate)
SELECT
i.BusinessEntityID,
ID,
GETDATE()
FROM inserted i
INNER JOIN @LastId AS l
ON l.Number = i.CardNumber
END
答案 1 :(得分:-1)
尝试使用光标。
Declare @cardtype int,
Declare @cardnumber int ,
Declare @expmonth int,
Declare @expyear int,
Declare @cursor CURSOR
Set @cursor = cursor FAST_FORWARD
for
select i.CardType,i.CardNumber,i.ExpMonth,i.ExpYear,GETDATE() from inserted i
Open cursor
FETCH NEXT from @cursor into @cardtype, @cardnumber, @expmonth, @expyear
WHILE @@fetch_status=0
BEGIN
-- your statement
FETCH NEXT from @cursor into @cardtype, @cardnumber, @expmonth, @expyear
END
close @cursor
deallocate @cursor