2013-05-07 76 views
0

好傢伙我已經試圖插入一個名爲dbo.filemetadata.Source列下面的代碼的結果,這裏是代碼:如何在表中更新或插入CTE。 SQL

WITH CTE AS 
(
    SELECT 
    rn, 
    ROW_NUMBER() OVER (PARTITION BY rn ORDER BY (SELECT NULL)) filepartno, 
    Split.a.value('.', 'VARCHAR(100)') AS filepart 
    FROM 
    (
    SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) rn, 
    CAST ('<M>' + REPLACE(FilePath, '\', '</M><M>') + '</M>' AS XML) AS String 
    FROM FileMetadata 
) AS A 
    CROSS APPLY String.nodes ('/M') AS Split(a) 
) 
SELECT FilePart AS A 

FROM CTE C 
    JOIN (SELECT MAX(filepartno) maxfilepartno, rn 
     FROM CTE 
     GROUP BY rn) C2 ON C.rn = C2.rn AND C.filepartno = C2.maxfilepartno-1; 

回答

3

您可以結合INSERT和CTE選擇與正常查詢:

WITH CTE AS 
(
.... 
) 
INSERT INTO ... 
SELECT FilePart AS A 

FROM CTE .... 

更新的UPDATE聲明

WITH CTE AS 
(
.... 
) 
UPDATE FileMetaData 
SET SOURCE = FilePart 

FROM FileMetaData INNER JOIN CTE ON .... 
+0

'我可以插入現在使用插入FileMetadata(SOURCENAME) SELECT FilePart FROM標籤Ç JOIN(SELECT MAX(filepartno)maxfilepartno,氡 FROM標籤 GROUP BY RN)C2 ON C.rn = C2.rn AND C.filepartno = 4,但我需要插入來匹配元數據中的文件..不是它只是插入文件元數據中的全新行。 – user2183502 2013-05-07 19:09:15

+0

因此,基本上你需要根據CTE和FileMetadata中的通用值更新元數據中的現有字段? – 2013-05-07 19:14:22

+0

正確,多數民衆贊成我認爲我需要,我已經嘗試了幾個插入,但它不工作。 – user2183502 2013-05-07 19:16:43