SQL SERVER Update table from tables with increment on some fields based on max

32 Views Asked by At

Table 1 -- Where information will be finally stored Table 2 -- Updated information from Access

Table 1 :

ProJ# LOC_ID OBJ_ID OBJ_U_ID OBJ_TYPE OBJ_# OBJ_V
A 1 1 1 A 1 1
A 1 4 4 A 3 null
A 1 5 5 A 4 null
A 1 2 2 B 1 1
A 2 1 1 A 1 1
A 2 2 2 A 2 1
A 1 2 2 A 2 Null
A 1 3 3 B 2 1
A 1 2 2nd 2nd C 1 null

Table 2:

LOCID OBJ# OBJV
1 1 3
1 2 3
2 1 3
2 2 3
2 3 3
1 3 3
1 4 3
2 4 3
1 5 3

so what I am trying to do is update Table 1 with information from Table 2 if the LOCID = LOC_ID and OBJ# = OBJ_# and OBJ_TYPE = 'A' Update Set OBJ_V = OBJV if not match insert into table 1. this is where i run into problems.

so on insert i need to get max(OBJ_ID) and +1 for every entry that will be inserted into table 1 from table 2.

my issue is that i runinto is that it will set them all to the same number. ex: MAX(OBJ_ID ) will be 5 so next should be 6 then 7 ect... but i get 6,6,6,6,6,6,6,6,6 etc.. OBJ_ID , OBJ_U_ID are the same for all OBJ_TYPE except C.

here is what im trying:

MERGE Table1 as T1 Using (
Select @PRoJect as ProN, OBJV, LOCID, OBJ# from TABLE2 where OBJ# is not null) AS S2
on
(T1.OBJ_# = S2.OBJ# and T1.LOC_ID = S2.LOCID and T1.PorJ# = S2.ProN and T1.OBJ_TYPE = 'A')
When Matched then Update Set
    T1.OBJ_V  = S2.OBJV
When Not Matched then Insert (
ProJ# , LOC_ID , OBJ_ID , OBJ_U_ID , OBJ_TYPE , OBJ_#  , OBJ_V
) Values (
@PRoJect , s2.locID , "NEED HELP HERE",  "NEED HELP HERE" , S2.OBJ#, S2.OBJV
); 

i have tried many things none get me a result that is right.

I have tried multiple things to get this to work. some partial work but then break bad.

what im trying to get out is:

Sequential number for OBJ_ID on max value on insert. so if max is 5 for LOC_ID = 1 and 2 for LOC_ID = 2 on insert it would look similar to this:

LOC_ID OBJ_ID
1 6
1 7
2 3
2 4
1 8
1 9
2 5
2 6
1 10

the can be more the 2 LOC_ID

0

There are 0 best solutions below