| Author |
Topic |
|
ttran
Starting Member
23 Posts |
Posted - 2007-05-21 : 20:33:16
|
| Could someone help me with this case?I have two tables, tbl1 and tbl2. I want to insert into tbl2 all the rows from tbl1 start with last seq# of tbl2 + 1. Both tables have primary key is pid+sqtbl1pid tst pt sc sq1 C 1 30 11 C 2 20 21 C 1 25 32 B 4 15 12 B 5 35 23 C 1 25 13 C 4 20 2tbl2pid tst pt sc sq1 A 5 50 11 A 6 30 22 A 5 10 12 A 4 20 2The result would be:tbl2pid tst pt sc sq1 A 5 50 11 A 6 30 21 C 1 30 31 C 2 20 41 C 1 25 52 A 5 10 12 A 4 20 22 B 4 15 32 B 5 35 43 C 1 25 13 C 4 20 2What I did is to create a view to find the max(sq) on tbl2 for each pid, then insert into tbl2 from tbl1 based on the max(sq) of the view, plus 1. I got the error: "Violation of Primary Key contraint. Cannot insert duplicate key in object dbo.tbl2."Seems like the insert statement uses the same value of max(sq) instead of increase 1 after each insertingcreate view maxsq asselect pid,max(sq) as sqfrom tbl2group by pidinsert into tbl2(pid,tst,pt,sc,sq)select a.pid,a.tst,a.pt,a.sc, case when (b.sq is null) then 1 else (b.sq + 1) endfrom tbl1 a left outer join maxsq b on a.pid = b.pidI really appreciate if someone can help me.Thanks in advance.--ttran |
|
|
khtan
In (Som, Ni, Yak)
17689 Posts |
Posted - 2007-05-21 : 21:43:43
|
[code]declare @tbl1 table( pid int, tst char(1), pt int, sc int, sq int)insert into @tbl1select 1, 'C', 1, 30, 1 union allselect 1, 'C', 2, 20, 2 union allselect 1, 'C', 1, 25, 3 union allselect 2, 'B', 4, 15, 1 union allselect 2, 'B', 5, 35, 2 union allselect 3, 'C', 1, 25, 1 union allselect 3, 'C', 4, 20, 2declare @tbl2 table( pid int, tst char(1), pt int, sc int, sq int)insert into @tbl2select 1, 'A', 5, 50, 1 union allselect 1, 'A', 6, 30, 2 union allselect 2, 'A', 5, 10, 1 union allselect 2, 'A', 4, 20, 2insert into @tbl2 (pid, tst, pt, sc, sq)select t1.pid, t1.tst, t1.pt, t1.sc, new_sq = isnull(l.last_sq, 0) + (row_number() over (partition by t1.pid order by t1.sq))from @tbl1 t1 left join ( select pid, last_sq = max(sq) from @tbl2 group by pid ) l on t1.pid = l.pidselect *from @tbl2order by pid, sq/* resultpid tst pt sc sq ----------- ---- ----------- ----------- ----------- 1 A 5 50 11 A 6 30 21 C 1 30 31 C 2 20 41 C 1 25 52 A 5 10 12 A 4 20 22 B 4 15 32 B 5 35 43 C 1 25 13 C 4 20 2(11 row(s) affected)*/[/code] KH |
 |
|
|
ttran
Starting Member
23 Posts |
Posted - 2007-05-22 : 12:00:43
|
| Thank you so much.You're awesome. You don't know how much it helps me. I know this request will be on my desk again and again.--ttran |
 |
|
|
|
|
|