SQL Server:如何使用select caluse

时间:2017-07-22 08:34:17

标签: sql-server-2008 insert-into

我遇到麻烦,从具有标量函数调用的select语句插入数据。我在下面发布了示例脚本,并在评论中提供了一些解释和问题。

---target table (in my case, this is not table variable, but a regular table, here for simplicity to posted this code as table variable to get the idea)
declare @tblItems table (
  Id int identity(1,1)
 ,ItemID int
 ,TranNo varchar(20)
 ,Qty decimal(18,3)
 ,SomeCalculatedValue decimal(18,3) 
)

--a dummay temp table, works like a source table
declare @tblTemp table (
  Id int identity(1,1)
 ,ItemID int
 ,TranNo varchar(20)
 ,Qty decimal(18,3)
 ,SomeCalculatedValue decimal(18,3) 
)
--put some dummy data in target table
insert into @tblItems(ItemID, TranNo, Qty, SomeCalculatedValue)
values
(1, 'GRN-001', 10, 0),
(2, 'GRN-002', 20, 0),
(3, 'GRN-003', 15, 0),
(4, 'GRN-004', 32, 0),
(5, 'GRN-005', 18, 0)
;

--insert 3 new rows in temp table, which later I want to insert in target table
insert into @tblTemp(ItemID, TranNo, Qty, SomeCalculatedValue)
values
(1, 'GRN-006', 6, 0), -- this line is working work fine,
(1, 'GRN-007', 3, 0), -- but this line is having problem, because it is not considering the last line( with TranNo='GRN-006' )
(2, 'GRN-008', 8, 0)

--here is the actual work, I need to read data from temp table to target table
--and the key requirement is the column 'SomeCalculatedValue'
--it should call a scalar function, and within that function I have to perform some calculations based on same target table
--for each ItemID passed, that scalar function will works as: it performs some sort of calculations on existing rows 
--for that particular ItemID, to simplify the understanding you can think of it as Running-Total(not actually running total, but concept 
--is same that each row value will based on previous row value) 

insert into @tblItems(ItemID, TranNo, Qty, SomeCalculatedValue)
select 
 ItemID
,TranNo
,Qty
,[dbo].[GetCalculatedValue] (ItemID, Qty) as SomeCalculatedValue -- this function will perform some calcualations
from @tblTemp


select * from @tblItems

我有两个表,@tblItems@tblTemp。我必须从@tblTemp@tblItems插入行,但是在@tblTemp的select子句中,我使用了一个标量函数,比如GetCalculatedValue(ItemID, Qty),它为特定的{{执行一些计算1}}来自目标表,并且对于每一行,它计算应插入ItemID的值。它不是真正的Running-Total,但为了理解它可以将其视为运行总计,因为每个行值将取决于前一行。

问题是当@tblItems对于特定的@tblTemp有超过1行时,它应该考虑已插入的行,但我认为这个insert-into-select语句将插入所有行一次,所以它没有考虑特定ItemID的最后一行是否在同一个select语句中。您可以查看代码,我也发布了一些评论以供解释。

0 个答案:

没有答案