我的“合并”出现问题:MERGE 语句多次尝试更新或删除同一行。
有人可以帮我解决这个问题,因为我不明白如何解决这个问题:
ALTER PROCEDURE [Files].[ImportFiles]
AS
-- Create a temporary table for the bulk import
CREATE TABLE #TempImportFileTable(
[fileID] [bigint] IDENTITY(1,1) NOT NULL,
[FileName] [nvarchar](max) NULL,
[FilePath] [nvarchar](max) NULL,
[FullPath] [nvarchar](max) NULL,
[FileSize] [nvarchar](max) NULL,
[FileExtension] [nvarchar](max) NULL,
[FileCreated] [nvarchar](max) NULL,
[FileLastAccessed] [nvarchar](max) NULL,
[FileModified] [nvarchar](max) NULL
CONSTRAINT [PK_fileID1] PRIMARY KEY CLUSTERED
(
[fileID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY];
-- Import into the temp table
BULK INSERT #TempImportFileTable FROM 'C:\Program Files\o7th FileSystem to DB\import.txt'
WITH(KEEPIDENTITY, FIELDTERMINATOR =',', ROWTERMINATOR = '\n');
-- Delete the Duplicate entries
DELETE FROM #TempImportFileTable WHERE fileID NOT IN (SELECT MAX(fileID) FROM #TempImportFileTable GROUP BY FullPath);
-- Now Merge the 2 tables
MERGE [Files].[File] AS TargetTable
USING #TempImportFileTable AS SourceTable
ON (TargetTable.FullPath = SourceTable.FullPath)
WHEN NOT MATCHED BY TARGET
THEN INSERT (FileName, FilePath, FileSize, FileExtension, FileCreated, FileLastAccessed, FileModified)
VALUES(SourceTable.FileName, SourceTable.FilePath, SourceTable.FileSize, SourceTable.FileExtension, SourceTable.FileCreated, SourceTable.FileLastAccessed, SourceTable.FileModified)
WHEN MATCHED
THEN UPDATE SET
TargetTable.FileName = SourceTable.FileName,
TargetTable.FilePath = SourceTable.FilePath,
TargetTable.FileSize = SourceTable.FileSize,
TargetTable.FileExtension = SourceTable.FileExtension,
TargetTable.FileCreated = SourceTable.FileCreated,
TargetTable.FileLastAccessed = SourceTable.FileLastAccessed,
TargetTable.FileModified = SourceTable.FileModified;