尝试批量插入或更新存储过程,这些过程对于大型记录集将高效而快速地运行。
我相信在存储过程中使用合并功能可能是批量插入或更新的最快方法。
但是,尝试编译存储过程时遇到错误,但是不确定我在做什么错。
我遇到以下错误:
列名或提供的值数与表定义不匹配。
这是示例代码:
IF EXISTS (SELECT name FROM sys.procedures WHERE name = 'AddOrUpdateRecords')
BEGIN
DROP PROCEDURE AddOrUpdateRecords;
PRINT 'Drop AddOrUpdateRecords Stored Procedure'
END
GO
IF EXISTS (SELECT name FROM sys.types WHERE name = 'RecordList')
BEGIN
DROP TYPE RecordList;
PRINT 'Drop RecordList Type';
END
GO
CREATE TYPE RecordList
AS TABLE
(
Code varchar(255) NOT NULL UNIQUE,
Name varchar(max) NOT NULL,
GeneratedDate date NULL
);
GO
PRINT 'Created RecordList Type';
GO
CREATE PROCEDURE AddOrUpdateRecords
@List AS RecordList READONLY
AS
BEGIN
SET NOCOUNT ON;
MERGE dbo.Records AS tgt
USING @List AS src
ON tgt.Code = src.Code
WHEN MATCHED THEN
UPDATE SET tgt.Name = src.Name, tgt.GeneratedDate = src.GeneratedDate
WHEN NOT MATCHED THEN
INSERT VALUES(src.Code, src.Name, src.GeneratedDate);
END
GO
PRINT 'Created AddOrUpdateRecords Stored Procedure';
GO
答案 0 :(得分:2)
在[不匹配]的情况下,您需要指定在insert语句中分配了值的列。例如
when not matched then
insert (col1, col2, col3)
values (src.Code, src.Name, src.GeneratedDate);