tags:

views:

60

answers:

1

i have got two table

create table t1(cid int, isnews int)

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

situations is like this: if t2 contain t2.cid = t1.cid then the t2.isnews = t1.news and if t2 not contain cid of t1 then new record should be inserted in t2 and that t1.cid, t1.isnews should be inserted in t2..

and complete table should be done in single query... i have done the updation part but not able to do insertion part..

update query:

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

i have prepared below cursor for insert... is it good? :

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
+1  A: 

I think this is the kind of thing you're after:

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

I've commented out the INSERT line - I recommend you run the SELECT on it's own first to check it does give you the correct result (all records from t1 that don't have a matching cid in t2).

I've assumed t2.nid is an IDENTITY column.

AdaTheDev
You people are doing noble job...really great help to every programmer
Rajesh Rolen- DotNet Developer