Sql Server - Using a CTE combining values from multiple tables without joining -


i've been using ctes build specially formatted tables need, has been working great long data comes 1 table or can join, presented situation in don't have common fields join on.

here ideal end-result

+------+---------+ | p_id | value   |  +------+---------+ | 1    | 1,55556 | | 2    | 2,1212  | | 3    | 2,6868  | | 4    | 2,4545  | | 5    | 1,55557 | | 6    | 2,1212  | | 7    | 2,6868  | | 8    | 2,4545  | +------+---------+ 

here sample tables

create table table1  ([emp_id] varchar(10)) ;  insert table1  ([emp_id]) values  (55556),   (55557) ;  create table table2  ([type] varchar(10), [type_id] varchar(10)) ;  insert table2  ([type], [type_id]) values  ('black', '1212'),  ('red', '6868'),  ('orange', '4545') ; 

here cte working single table

go cte (     select t1.[emp_id], c.value     table1 t1         outer apply (values             ('1,' + t1.[emp_id])        ) c(value) )  select     row_number() over(order [emp_id], value) p_id,     value cte 

but want this... except when i'm hit "the multi-part identifier "t1.emp_id" not bound"

go cte (     select t1.[emp_id], c.value     table1 t1, table2 t2         outer apply (values             ('1,' + t1.[emp_id]),             ('2,' + t2.type_id)        ) c(value) )  select     row_number() over(order [emp_id], value) p_id,     value cte 

now, have done before, make separate column each value except time dealing hundred of values in table2 need insert that's not practical anymore.

thanks in advance suggestions.

here how can desired output. have feeling i'm missing point:

with cte (   select '2,'+type_id value, emp_id   table1 t1, table2 t2    union    select '1,'+emp_id value, emp_id   table1   ) select value,   row_number() over(order emp_id, value) p_id cte 

Comments

Popular posts from this blog

android - Get AccessToken using signpost OAuth without opening a browser (Two legged Oauth) -

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: mockito -

google shop client API returns 400 bad request error while adding an item -