sql >> Base de Datos >  >> RDS >> Sqlserver

Extracto de columna DB y división para encontrar otro resultado de tabla

Bien pensado diría yo. Aquí hay una consulta para hacer algo así

SELECT 
t1.temp_id
   --  ... put your column list here from t2 and t3 here like t2.name
FROM table1 t1 
  LEFT JOIN table2 t2 
     ON CAST(LEFT(t1.temp_id,CHARINDEX(':',t1.temp_id)-1) AS INT)=t2.ID
  LEFT JOIN table3 t3 
     ON CAST(RIGHT(t1.temp_id,CHARINDEX(':',REVERSE(t1.temp_id))-1) AS INT)=t3.ID

Aquí hay un pequeño script para probar esto también

create table table1 (temp_id varchar(10))
insert into table1 values('1:1'),('21:2'),('1:22'),('1:'),(':2')

create table table2 (id int, value varchar(2))
insert into table2 values (1,'1'),(21,'21'),(1,'1')

create table table3 (id int, value varchar(2))
insert into table3 values (1,'1'),(2,'2'),(22,'22')

Salida PD:tenga en cuenta el null manejo en la salida