0

有很多问题可以涵盖此错误,但我遇到的问题是:

A)我目前正在进行合并(带有插入)

B)我没有明确设置身份列!

我的存储过程(表名和属性混淆):

表定义

CREATE TABLE MyTable (
    [ID] BIGINT IDENTITY(1, 1) NOT NULL,
    [Value] NVARCHAR (256) NOT NULL,
    [Property] NVARCHAR (256) NOT NULL,
    CONSTRAINT [PK_MyTable] PRIMARY KEY CLUSTERED ([ID] ASC),
    CONSTRAINT [IX_MyTable] UNIQUE NONCLUSTERED ([Value] ASC)
);

存储过程定义

CREATE TYPE TempType as Table (
    [TempValue] nvarchar(256) NOT NULL,
    [TempProperty] nvarchar(256) NOT NULL,
);
GO

CREATE PROCEDURE [Name]
    @Source TempType READONLY
AS
BEGIN
    MERGE [MyTable] as target
    USING (SELECT * FROM @Source) as source (TempValue, TempProperty)
    ON (target.Value = source.TempValue)
    WHEN MATCH THEN
        UPDATE SET Value = source.TempValue, Property = source.TempProperty
    WHEN NOT MATCHED THEN
        INSERT ([Value], [Property])
        VALUES (source.TempValue, source.TempProperty)
        OUTPUT deleted.*, $action, inserted.* INTO [MyTable];

END

据我所知,我没有在任何地方明确指定该IDENTITY列。我正在指定一个UNIQUE-ly 约束列。

最后,与错误所说的相反,指定IDENTITY_INSERT ON什么都不做。

编辑:我还应该指定,从.dacpac通过 C# 部署时出现此错误。

4

1 回答 1

0

我会简单地摆脱 MERGE 语句(设计上有很多问题)并使用如下简单的插入语句:

CREATE PROCEDURE [Name]
    @Source TempType READONLY
AS
BEGIN
  SET NOCOUNT ON;

    INSERT INTO [MyTable] ([Value], [Property])
    SELECT s.TempValue, s.TempProperty 
    FROM @Source s
    WHERE EXISTS (SELECT 1 
                  FROM [MyTable]  
                  WHERE Value = s.TempValue)

END

要阅读有关 MERGE 语句的问题,请查看这篇文章Use Caution with SQL Server's MERGE Statement

由于您已在 Merge 语句中添加了更新,现在我还将添加一条更新语句并将更新包装并插入到一个事务中,但我仍然不建议使用合并语句。

CREATE PROCEDURE [Name]
    @Source TempType READONLY
AS
BEGIN
  SET NOCOUNT ON;


BEGIN TRANSACTION;

     UPDATE T
       SET T.[Property] = S.[Property]
     FROM [MyTable] T 
     INNER JOIN @Source s ON T.Value = s.TempValue



    INSERT INTO [MyTable] ([Value], [Property])
    SELECT s.TempValue, s.TempProperty 
    FROM @Source s
    WHERE NOT EXISTS (SELECT 1 
                      FROM [MyTable]  
                      WHERE Value = s.TempValue)


COMMIT TRANSACTION;

END
于 2015-10-26T17:04:41.947 回答