使用参数合并到表中

时间:2018-04-18 08:49:09

标签: sql-server tsql parameters merge sql-insert

我被困住了,我知道这比我想象的要容易。

我有一个看起来像这样的表:

SELECT ID , NAME , CITY FROM TEMP

enter image description here

我创建了一个带参数的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 ='纽约')

enter image description here

我想使用MERGE()而不是"插入"如果可能的话。

2 个答案:

答案 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; }