使用SQL Server 2016合并功能

时间:2018-07-17 08:02:35

标签: sql-server merge insert

我有一个表 digital_calendar_event ,其列为: dce_date dce_event_name dce_event_icone

数据显示在可编辑的Datagrid中,可以在其中修改事件名称或Icone。我不知道它是更新还是插入(我不想使用ID,这里的日期是唯一的主键) 我听说Merge函数可以检查值是否存在,这里我的主键是 dce_date

另外,我需要检测用户是否已删除数据网格中的值( dce_event_name dce_event_icone

我想使用合并功能,但是我只有一个表,在合并中似乎需要一个源表...

编辑:我使用了IF EXIST语句,但是在 ELSE 部分,我似乎无法输入CASE WHEN语句

IF EXISTS (SELECT dce_date FROM digital_calendar_event where dce_date = @CurrentDate)
UPDATE digital_calendar_event set dce_event_name = @EventName, dce_event_icone = @EventIcone
--- incorrect syntax near 'CASE'
ELSE CASE 
   WHEN @EventName ='' and @EventIcone = '' THEN DELETE FROM digital_calendar_event WHERE dce_date = @CurrentDate
   WHEN @EventName <> '' or @EventIcone <> '' THEN INSERT INTO digital_calendar_event (dce_date, dce_event_name, dce_event_icone) VALUES(@CurrentDate, @EventName , @EventIcone)
END

如何这样做?我编写的SQL代码正是我所需要的,但是如果不起作用...

2 个答案:

答案 0 :(得分:1)

嗨,尝试使用以下查询-

IF EXISTS (SELECT dce_date FROM digital_calendar_event where dce_date = @CurrentDate)
Begin
UPDATE digital_calendar_event set dce_event_name = @EventName, dce_event_icone = @EventIcone

ELSE 

if  @EventName ='' and @EventIcone = '' 
Begin
DELETE FROM digital_calendar_event WHERE dce_date = @CurrentDate

ENd


   Else IF @EventName <> '' or @EventIcone <> '' 
   Begin
   INSERT INTO digital_calendar_event (dce_date, dce_event_name, dce_event_icone) VALUES(@CurrentDate, @EventName , @EventIcone)

   END
END

答案 1 :(得分:1)

感谢@Deepak Kumar,这是答案:

IF EXISTS (SELECT dce_date FROM digital_calendar_event where dce_date = @CurrentDate)
BEGIN
    IF  @EventName ='' and @EventIcone = '' 
        BEGIN
        DELETE FROM digital_calendar_event WHERE dce_date = @CurrentDate
        END
   ELSE UPDATE digital_calendar_event set dce_event_name = @EventName, dce_event_icone = @EventIcone
END
ELSE-- else of if exists
  BEGIN
    IF @EventName <> '' or @EventIcone <> '' 
    INSERT INTO digital_calendar_event (dce_date, dce_event_name, dce_event_icone) VALUES(@CurrentDate, @EventName , @EventIcone)
  END