如何从另一个表插入表并使用函数

时间:2019-03-19 22:23:02

标签: sql sql-server function sql-insert

我在下面尝试过,但是我违反了主键。

insert into a_c ([a_id],  [C_id], [ac_id])
  select  t2.A,t2.C , dbo.getac_id() from  table_2 t2

我也尝试使用游标不起作用。

DECLARE insert_cursor CURSOR FOR select  t2.A,t2.C from  table_2 t2

-- open cursor and fetch first row into variables
OPEN insert_cursor FETCH NEXT FROM insert_cursor into @cid,@aid

WHILE @@FETCH_STATUS=0
BEGIN
--insert into table row by row
insert into ing_spe.[dbo].ACTIVITY_CONTACT ( [A_ID],[C_ID], [A_C_ID]) SELECT @aid,@cid, dbo.getac_id() 
-- get next available row into variables
FETCH NEXT FROM insert_cursor into @cid,@aid

END
close insert_cursor
Deallocate insert_cursor
GO

注意: dbo.getac_id()返回单个值。它内部的逻辑执行一些计算,并在表a_c中获取ac_id的最大值,以返回唯一值。 列“ ac_id ”是主键。

**期望的输出**

[a_id],    [C_id],   [ac_id]
a1         c1          1011
a1         c2          1012
a2         c1          1013
a3         c4          1014

0 个答案:

没有答案