Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
Author |
Topic |
ttran
Starting Member
23 Posts |
Posted - 2006-10-02 : 17:26:14
|
Is it possible to insert records into a table with sequence number for each unique id? I want to insert into table-2 from table-1 but I don't know how to keep track of the sequence number on the table-2.Thank you for any help.table-1 (id is primary key)id subj1 subj2 subj3 subj41 ab ac ad ae2 bc bd 3 cd ca cbtable-2 (id + seq is primary key)id seq subj1 1 ab1 2 ac1 3 ad1 4 ae2 1 bc2 2 bd3 1 cd3 2 ca3 3 cbttran |
|
timmy
Master Smack Fu Yak Hacker
1242 Posts |
Posted - 2006-10-02 : 17:58:35
|
SELECT id, 1 as seq, subj1FROM table-1WHERE subj1 IS NOT NULLUNIONSELECT id, 2 as seq, subj2FROM table-1WHERE subj2 IS NOT NULLUNIONSELECT id, 3 as seq, subj3FROM table-1WHERE subj3 IS NOT NULLUNIONSELECT id, 4 as seq, subj4FROM table-1WHERE subj4 IS NOT NULL |
 |
|
ttran
Starting Member
23 Posts |
Posted - 2006-10-02 : 19:42:20
|
Thank you for your help. But if table-1 has up to 20 subj then I have to repeat the coding 20 times. I was hoping that maybe there is a way to use max(seq) function after insert a record in table-2, and add 1 to the max(seq) to generate the next seq.ttran |
 |
|
timmy
Master Smack Fu Yak Hacker
1242 Posts |
Posted - 2006-10-02 : 19:48:51
|
You could, but it would mean either dynamic SQL or a cursor. Neither of which are that good for performance. My example is a bulky statement but would probably be the fastest option for execution. Is this going to be a once-off normalisation or will you want to run this regularly? That will influence what approach you take. |
 |
|
ttran
Starting Member
23 Posts |
Posted - 2006-10-03 : 11:16:23
|
Your code will solve the first input file (table-1). But how can I insert the 2nd input file (table-3) into table-2, which might or might not have some seq for each id?table-3id subj1 subj2 subj3 subj41 x1 x2 x3 x42 x2 x3 x54 x1 x3 After insert, the table-2 will have:id seq subj1 5 x11 6 x21 7 x31 8 x42 3 x22 4 x32 5 x54 1 x14 2 x3 |
 |
|
madhivanan
Premature Yak Congratulator
22864 Posts |
|
ttran
Starting Member
23 Posts |
Posted - 2006-10-03 : 14:24:48
|
Awesome !!!Thank you, thank you.I'm new, but I learn a lot from this website.ttran |
 |
|
|
|
|
|
|