我被困住了,我知道这比我想象的要容易。
我有一个看起来像这样的表:
SELECT ID , NAME , CITY FROM TEMP
我创建了一个带参数的Merge语句,如果ID和City不存在则应该插入一个新行
ALTER PROCEDURE [dbo].[sp_TMP]
@ID INT,
@City NVARCHAR(50)
AS
MERGE TEMP AS TARGET
USING
(
SELECT
ID,
NAME,
CITY
FROM TEMP
) AS SOURCE
ON [TARGET].[ID]= @ID AND [TARGET].[City] = @City
WHEN NOT MATCHED THEN
INSERT
(
[ID],
[NAME],
[CITY]
)
VALUES
(
@ID,
[SOURCE].[NAME],
@City
);
我知道我在这里做错了,因为ALLA记录受到影响。
我希望得到一个结果(如果@ID =' 1'和@City ='纽约')
我想使用MERGE()而不是"插入"如果可能的话。
答案 0 :(得分:1)
首先,我想说这样的解决方案的一致性根本不好。
但是,为了使其按照您在评论中的描述工作,请更改代码:
ALTER PROCEDURE [dbo].[sp_TMP]
@ID INT,
@City NVARCHAR(50)
AS
MERGE TEMP AS TARGET
USING
(
SELECT
ID,
NAME,
CITY
FROM TEMP
) AS SOURCE
ON [TARGET].[ID]= @ID AND [TARGET].[City] = @City
WHEN NOT MATCHED THEN
INSERT
(
[ID],
[NAME],
[CITY]
)
VALUES
(
@ID,
(SELECT TOP(1) t.Name FROM TEMP t WHERE t.ID = @ID),
@City
);
应该做的伎俩。
另外,我不确定你为什么只想使用MERGE
,但这对于IF NOT EXISTS ... INSERT INTO
来说是个很好的选择:
ALTER PROCEDURE [dbo].[sp_TMP]
@ID INT,
@City NVARCHAR(50)
AS
IF NOT EXISTS (SELECT TOP(1) 1 FROM TEMP WHERE ID = @ID AND City = @City)
INSERT INTO TEMP(ID, City, Name)
VALUES (@ID, @City, (SELECT TOP(1) Name FROM TEMP WHERE ID = @ID));
答案 1 :(得分:0)
如果您使用代码优先方法,只需使用[Index(IsUnique = true)]试试这个.Ex:
[Required]
[Column(TypeName = "varchar")]
[StringLength(100)]
[Index(IsUnique = true)]
public string Name { get; set; }