2012-10-23 74 views
3

我有以下的臨時表結構:更新在一個臨時表中的列使用新值

CREATE TABLE #TempTable ( 
    ID INT, 
    CId TINYINT, 
    TagId INT, 
    Beginning_X DECIMAL(18,5), 
    Beginning_Y DECIMAL(18,5), 
    Ending_X DECIMAL(18,5), 
    Ending_Y DECIMAL(18,5)) 

INSERT INTO #TempTable (ID, CId, TagId, Beginning_X, Beginning_Y) 
SELECT ID, CId,TagId, X, Y 
    FROM Table_1 
WHERE IsRepeat = 1 

INSERT INTO #TempTable(Ending_X, Ending_Y) 
SELECT X,Y 
    FROM Table_1 t 
WHERE t.ID IN (SELECT ID+1 
        FROM Table_1 
       where IsRepeat = 1)) 

第二插入去除第一插入語句所有的價值觀和我想不通爲什麼。我想將第二次插入的結果追加到第一次插入,並有一個實體表。

編輯:我想我找到了解決辦法:

UPDATE t 
SET t.Ending_X = p.X, t.Ending_Y = p.Y 
FROM #TempTable t, Table_1 p 
WHERE p.ID IN (SELECT ID+1 FROM Table_1 where IsRepeat = 1) 
AND p.ID-1 = t.ID 
+0

聽起來像你想用你的第二個插入「UPDATE」。對?或者你真的想要一個新的行嗎? –

+0

沒有新行。我一直在嘗試不同的UPDATE語句,但我沒有得到任何地方。 – Mellonjollie

回答

4

我認爲你需要這個

UPDATE t 
SET Ending_X = X, Ending_Y = Y 
FROM #TempTable t 
WHERE t.ID IN (SELECT ID+1 FROM Table_1 where IsRepeat = 1)) 
+0

你把我放在正確的軌道上,我想我釘了它。 – Mellonjollie

1

如何unioning兩個查詢

INSERT INTO #TempTable (ID, CId, TagId, Beginning_X, Beginning_Y) 
SELECT ID, CId,TagId, X, Y 
from Table_1 
WHERE IsRepeat = 1 
    UNION 
SELECT Convert(Null, int) AS ID, Convert(Null, tinyint) AS CId, 
    Convert(Null, int) AS TagId, X,Y 
FROM Table_1 t 
WHERE t.ID IN (SELECT ID+1 FROM Table_1 where IsRepeat = 1)) 
相關問題