如何解决如何从临时表中获取最近插入的列的值?
您可以使用aCTE
来捕获NEWID()
为表的每个记录创建的值dbo.[Service]
。然后使用它CTE
来执行以下操作INSERT
:
;WITH ToInsert AS
(
SELECT ServiceId ,
ServiceRate,
ABS(CHECKSUM(NEWID())%3) + 1 AS Quantity
FROM dbo.[Service]
)
INSERT INTO dbo.[Transaction]
(
ReservationId,
ServiceId,
Rate,
Quantity,
Amount
)
SELECT @MinReservationId,
ServiceId,
ServiceRate,
Quantity,
ServiceRate * Quantity
FROM ToInsert
解决方法
我无法在Select语句中使用表的最近插入的Quantity
值#ACCT
来像
ser.ServiceRate * Quantity
每次我得到错误
无法将值NULL插入“金额”列中
我只是一个初学者,所以解决这个问题的任何指示都将有所帮助。
DECLARE @MinReservationId INT = (SELECT MIN(f.ReservationId) FROM dbo.Reservation AS f)
DECLARE @MaxReservationId INT = (SELECT MAX(f.ReservationId) FROM dbo.Reservation AS f)
DECLARE @QuantityNew INT
WHILE @MinReservationId <= @MaxReservationId
BEGIN
CREATE TABLE #Acct
(
ServiceId INT,Quantity INT --> I WANT THIS VALUE TO BE USED BELOW
)
INSERT INTO dbo.[Transaction]
(
ReservationId,ServiceId,Rate,Quantity,Amount
)
OUTPUT inserted.ServiceId,Inserted.Quantity
INTO #Acct
(
ServiceId,Quantity
)
SELECT
@MinReservationId,ser.ServiceId,ser.ServiceRate,ABS(CHECKSUM(NEWID())%3) + 1,ser.ServiceRate * (SELECT acc.Quantity from #Acct as acc) -> QUANTITY from #ACCT should be used here
FROM dbo.[Service] AS ser
SELECT @MinReservationId=@MinReservationId+1
Drop table #Acct
END
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。