简体   繁体   中英

Updating a column in a temp table with new values

I have the following temp table structure:

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))  

The second insert removes all the values from the first insert statement and I can't figure out why. I want to append the the results from the second insert to the first insert and have one solid table.

EDIT: I think I found the solution:

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

I think you need this

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)) 

How about unioning the two queries

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)) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM