0

So I saw some similar questions here but I just could not understand them.

My table:

'timestamp' int(30) NOT NULL,
'clientguid' varchar(32) NOT NULL,
'clientip' varchar(32) NOT NULL,
'serverip' varchar(32) NOT NULL)

I have 4 variables

$TimeStamp
$ClientGUID
$ClientIP
$ServerIP

My query should do this: if there is a row with clientguid that matches $ClientGUID:

UPDATE 'mytablename'
SET 'timestamp' = '$TimeStamp','clientip' = '$ClientIP','serverip' = '2.2.2.24'
WHERE 'mytablename'.'clientguid' = '$ClientGUID');

If there is not a row matching that:

INSERT INTO 'mytablename' ('timestamp','clientguid','clientip','serverip') 
VALUES($TimeStamp,'$ClientGUID', '$ClientIP', '$ServerIP');

I don't have to worry about escaping and validating, that has already been done I just need a statement that will accomplish this. :)

8
  • That post is SQL Server 2008, not SQLite :P Commented Oct 4, 2014 at 15:29
  • or stackoverflow.com/questions/418898/… ......................... Commented Oct 4, 2014 at 15:29
  • see @edelwater's duplicate suggestion then... doesn't look like you're the first one having asked this one... search is your good friend ;) Commented Oct 4, 2014 at 15:31
  • edelwater, I saw this question but I'm unsure how to specify which column I want to look for a match on. If I just do this update SQL command, then is it updating the first row with a matching server ip? client ip? I would specifically like to do it by client GUID. Commented Oct 4, 2014 at 15:32
  • In 418898 notice the "select" in the answer Commented Oct 4, 2014 at 15:39

2 Answers 2

0

If you set unique key on your table, then you can first do it insert and if error duplicity record then catch them and do it update. This usually faster then some how first existence of row and then do it update.

Sign up to request clarification or add additional context in comments.

Comments

-1

Create an UNIQUE index for colomn clientguid Then tou can use INSERT .... ON DUPLICATE KEY UPDATE

INSERT INTO yourtable (timestanp, clientguid,clientip, serverip)
VALUES(NOW(), $clientguid, '$clientip', '$serverip')
ON DUPLICATE KEY UPDATE
    timestamp = NOW(),
    clientip = VALUES(clientip),
    serverip = VALUES(serverip)

1 Comment

This does not work in SQLite.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.