您好我需要一个脚本,根据ID更新另一个表中的行,然后从第二个表中删除它复制的数据。
这是我的表
Documents
--------
DocumentID(PK)
RealFileName
FileName
ImageDocuments
--------------
ImageDocumentId(PK)
DocumentId(FK)
OriginalFileName
StorageFileName
两个表之间的映射是一对一的。
目前我有更新表的脚本,但我不知道如何从文档表中删除值。这是我到目前为止所做的:
UPDATE [dbo].[ImageDocuments]
SET [dbo].[ImageDocuments].[OriginalFileName] = d.FileName,
[dbo].[ImageDocuments].[StorageFileName] = d.RealName
FROM [dbo].[ImageDocuments] as fu,
[dbo].[Documents] as d
WHERE fu.DocumentID = d.DocumentID
如何从文档表中删除添加到ImageDocuments表的行?
更新 我创建了一个删除查询,任何人都可以验证这是否可行corectly:
DELETE [dbo].[Documents]
FROM [dbo].[ImageDocuments] as fu
INNER JOIN [dbo].[Documents] as d ON d.DocumentID = fu.DocumentID
答案 0 :(得分:1)
使用此:
UPDATE [dbo].[ImageDocuments]
SET [dbo].[ImageDocuments].[OriginalFileName] = d.FileName,
[dbo].[ImageDocuments].[StorageFileName] = d.RealName
OUTPUT INSERTED.ImageDocumentId
INTO @Ids
FROM [dbo].[ImageDocuments] as fu,
[dbo].[Documents] as d
WHERE fu.DocumentID = d.DocumentID;
DELETE FROM Documents
WHERE DocumentID IN (SELECT ImageDocumentId FROM @IDs);
答案 1 :(得分:0)
我认为这应该有用。
由于您已经复制了ImageDocuments中的所有行,因此可以安全地删除文档中的所有DocumentID
UPDATE [dbo].[ImageDocuments]
SET [dbo].[ImageDocuments].[OriginalFileName] = d.FileName,
[dbo].[ImageDocuments].[StorageFileName] = d.RealName
FROM [dbo].[ImageDocuments] as fu,
[dbo].[Documents] as d
WHERE fu.DocumentID = d.DocumentID;
Delete From Documents where Documents.DocumentID in
(Select ImageDocuments.DocumentID from ImageDocuments);
答案 2 :(得分:0)
我会使用临时表来存储两个表中的匹配记录。然后,通过使用该临时表,您可以删除已在其他表中使用过的数据。
如;
DECLARE @Table TABLE (MatchingId INT)
INSERT INTO @Table
SELECT DocumentID FROM [ImageDocuments] ImgDoc
INNER JOIN [Documents] doc
ON ImgDoc.DocumentID = doc.DocumentID
UPDATE [dbo].[ImageDocuments]
SET [dbo].[ImageDocuments].[OriginalFileName] = d.FileName,
[dbo].[ImageDocuments].[StorageFileName] = d.RealName
FROM [dbo].[ImageDocuments] as fu,
[dbo].[Documents] as d
WHERE fu.DocumentID = d.DocumentID
DELETE FROM DocumentID WHERE DocumentID IN
(SELECT DocumentID FROM @Table )