2012-10-16 6 views
1

를 사용하여 표 2에서 레코드와 표를 업데이트하는 방법 :내가 두 테이블이 T-SQL

Table1 :

RulesVectorID(nullable, primary),Weight,IsDeleted 

Table2 :

RulesVectorID(forigen) , Weight,IsDeleted, NumberOfOffers, other fields... 

내가 견인 작업을 수행 할 :

  1. where RulesVectorID ==null

    의 모든 행에 Id를 할당 나는 노력이 : 단계에서 추가 행

    UPDATE myTable1 
    SET RulesVectorID = SELECT MAX(RulesVectorID) + 1 FROM myTable1, 
    WHERE RulesVectorID IS NULL 
    
  2. (1) 내가 그들의 NumberOfOffers

    에 1을 자신의 Weight, IsDeleted 열을 복사하고 추가 할 나는 이것을 시도했다 :

    INSERT INTO myTable2 (Weight, IsDeleted, NumberOfOffers, RulesVectorID) 
    VALUES (
        SELECT Weight, IsDeleted, 1, RulesVectorID 
        FROM myTable1 
        WHERE myTable1.RulesVectorID NOT IN (SELECT RulesVectorID FROM myTable2)) 
    

더 깨끗한 방법이 있습니까? 당신이 드롭하면

+0

더 깨끗한 방법이 있는지 물어 보면 작품이 있다는 뜻입니까? 작동하는 경우 사용하십시오. 꽤 합리적입니다. 테이블을 수정 한 후 RulesVectorID를 자동 증가로 변경하고 기본 키로 만들어 Null을 허용하지 않습니다. –

답변

0
;with t as (
select *, rn=row_number() over (order by weight) 
from mytable1 
where RulesVectorID is null) 
update t set RulesVectorID = rn + isnull((Select max(RulesVectorID) from myTable1),0); 

두 번째 쿼리는 괜찮아 보이는 values()

insert into myTable2 (Weight,IsDeleted,NumberOfOffers,RulesVectorID) 
select Weight,IsDeleted,1,RulesVectorID 
from myTable1 
where myTable1.RulesVectorID not in (select RulesVectorID from myTable2) 
+0

왜 '(순서대로)'가 필요합니까? –

+0

왜'values ​​()'는 괜찮습니까? –

1

각 테이블의 컬럼 [된 uniqueID]에 인덱스가 있고 그냥 데이터 표 1의 기존 행을 업데이트 할 감안할 때 표 2와 [된 uniqueID] 두 테이블 사이의 동일 있어야되는 다음과 같은 시도 할 수 있습니다 :

UPDATE Table1 
SET Table1.stfips=Table2.NEWstfips, 
    Table1.areatype=Table2.NEWareatype, 
    Table1.area=Table2.NEWarea 
FROM Table2 
JOIN Table1 
    ON Table1.uniqueid=Table2.uniqueid 

우리는 우리의 준비 데이터베이스에 이것을 사용 속도가 공동의 위대한되지 않도록 ncern. 1300 만 레코드의 엔벨로프 테스트를 보면 하드웨어 (YMMV)에서 약 15 초 걸리는 것으로 나타났습니다.