Pregunta

Tengo dos tabla

create table t1(cid int, isnews int)

create table t2(nid int,cid int, isnews int)

situaciones es la siguiente:   si t2 contienen t2.cid = t1.cid entonces el t2.isnews = t1.news y Si T2 no contiene cid de t1 a continuación, nuevo récord se debe insertar en t2 y que t1.cid, t1.isnews deben insertarse en t2 ..

y la tabla completa debe hacerse en consulta única ... que he hecho la parte updation pero no es capaz de hacer parte de inserción ..

Consulta de actualización:

 UPDATE    t22
SET       t22.isnews = t11.isnews 
FROM      t2 AS t22
    JOIN  t1 AS t11
    ON  t11.cid= t22.cid

He preparado por debajo del cursor de inserción ... ¿es bueno? :

DECLARE @clntid INT
DECLARE @clntnewsltr INT
DECLARE clientnews CURSOR FOR 
SELECT clientid,newsLetter 
FROM clients 
WHERE clientid NOT IN (SELECT clientid FROM clientprivacy) 

OPEN clientnews  
FETCH NEXT FROM clientnews INTO @clntid,@clntnewsltr  

WHILE @@FETCH_STATUS = 0  
BEGIN  

   INSERT INTO clientprivacy (clientId,tdNewsLetters) VALUES(@clntid, @clntnewsltr)
 FETCH NEXT FROM clientnews INTO @clntid,@clntnewsltr  
END  

CLOSE clientnews  
DEALLOCATE clientnews
¿Fue útil?

Solución

creo que este es el tipo de cosa que está buscando:

--INSERT t2 (cid, isnews)
SELECT t1.cid, t1.isnews
FROM t1
    LEFT JOIN t2 ON t1.cid = t2.cid
WHERE t2.cid IS NULL

he comentado a cabo la línea INSERT -. Te recomiendo que ejecuta el SELECT en su propio primero para comprobar que no le dan el resultado correcto (todos los registros de t1 que no tienen un cid coincidente en t2)

t2.nid he asumido es una columna de identidad.

Otros consejos

será mucho mejor sin cursores cursores :) toman mucho más tiempo para funcionar en grandes conjuntos de datos.

Es cierto que usted puede utilizar un LEFT JOIN, pero también se puede utilizar un SELECT en la cláusula WHERE. La mayoría de las veces se trata de una elección de estilo.

CREATE TABLE table1(col_1 int, col_2 int)
CREATE TABLE table2(nid int, col_1 int, col_2 int)


INSERT INTO table2 (col_1,col_2) 
SELECT col_1,col_2 
FROM table1 
WHERE col_1 NOT IN (SELECT col_1 FROM table2) 
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top