SQL Server 2008 - IF NOT EXISTS INSERT ELSE UPDATE

后端 未结 4 1014
一向
一向 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:22

    IF NOT EXISTS(SELECT * FROM Clock
    WHERE clockDate = '08/10/2012') AND userName = 'test')
    

    Has an extra parenthesis. I think it's fine if you remove it:

    IF NOT EXISTS(SELECT * FROM Clock WHERE
    clockDate = '08/10/2012' AND userName = 'test')
    

    Also, GETDATE() will put the current date in the column, though if you don't want the time you'll have to play a little. I think CONVERT(varchar(8), GETDATE(), 112) would give you just the date (not time) portion.

    IF NOT EXISTS(SELECT * FROM Clock WHERE
    clockDate = CONVERT(varchar(8), GETDATE(), 112)
    AND userName = 'test')
    

    should probably do it.

    PS: use a merge statement :)

提交回复
热议问题