我无法在 Select 语句中使用 #ACCT
表的最近插入的 Quantity
值
ser.ServiceRate * Quantity
每次我得到错误
Cannot insert the value NULL into column 'Amount'
我只是一个初学者,所以任何解决这个问题的建议都会有所帮助。
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
最佳答案
您可以使用 CTE
来捕获为表 dbo.[Service]
的每条记录创建的 NEWID()
值。然后使用此 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
关于sql - 如何从临时表中获取最近插入的列的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49584549/