如何在表中更新或插入CTE。 SQL

时间:2013-05-07 18:16:15

标签: sql sql-server

Hello Guys我一直试图在名为dbo.filemetadata.Source的列中插入以下代码的结果,这里是代码:

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;

1 个答案:

答案 0 :(得分:3)

您可以在CTE中将INSERT和SELECT组合为普通查询:

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