SQL Server 2008 - IF NOT EXISTS INSERT ELSE UPDATE

后端 未结 4 1015
一向
一向 2020-11-29 00:54

I apologize, but this is kind of a two part question.

I\'m extremely new to SQL and am trying to develop a time clock application for the small office that I work in

4条回答
  •  时光说笑
    2020-11-29 01:32

    As others have suggested that you should look into MERGE statement but nobody provided a solution using it I'm adding my own answer with this particular TSQL construct. I bet you'll like it.

    Important note

    Your code has a typo in your if statement in not exists(select...) part. Inner select statement has only one where condition while UserName condition is excluded from the not exists due to invalid brace completion. In any case you cave too many closing braces.

    I assume this based on the fact that you're using two where conditions in update statement later on in your code.

    Let's continue to my answer...

    SQL Server 2008+ support MERGE statement

    MERGE statement is a beautiful TSQL gem very well suited for "insert or update" situations. In your case it would look similar to the following code. Take into consideration that I'm declaring variables what are likely stored procedure parameters (I suspect).

    declare @clockDate date = '08/10/2012';
    declare @userName = 'test';
    
    merge Clock as target
    using (select @clockDate, @userName) as source (ClockDate, UserName)
    on (target.ClockDate = source.ClockDate and target.UserName = source.UserName)
    when matched then
        update
        set BreakOut = getdate()
    when not matched then
        insert (ClockDate, UserName, BreakOut)
        values (getdate(), source.UserName, getdate());
    

提交回复
热议问题