Rares
Rares

Reputation: 97

if exists update else insert

I want to know if the next piece of code is correct:

 SqlCommand cmd = new SqlCommand(
   "IF NOT EXISTS(SELECT count(*) from Raspunsuri where id_intrebare=2)" +
   "Insert INTO Raspunsuri VALUES(@raspuns,@cnp,@data,2,@ip,@idsesiune)" +
   "else" +
   "UPDATE Raspunsuri SET raspuns=@raspuns,cod_numeric_personal=@cnp,data_raspuns=@data,id_intrebare=2,ip_user=@ip,id_sesiune=@idsesiune WHERE id_intrebare=2", con);

All the parameters are correct that I want to insert but it seems this piece of code doesn't do the insert or update.Do you have any suggestions?it's a sql query combined with c#..

Upvotes: 0

Views: 13835

Answers (5)

dknaack
dknaack

Reputation: 60438

Description

No because you select count that has always a value.

select a column or * instead.

Sample

SqlCommand cmd = new SqlCommand(
   "IF NOT EXISTS(SELECT id_intrebare from Raspunsuri where id_intrebare=2) " +
   "Insert INTO Raspunsuri VALUES(@raspuns,@cnp,@data,2,@ip,@idsesiune) " +
   "else " +
   "UPDATE Raspunsuri SET raspuns=@raspuns,cod_numeric_personal=@cnp,data_raspuns=@data,id_intrebare=2,ip_user=@ip,id_sesiune=@idsesiune WHERE id_intrebare=2", con);

Upvotes: 3

Hans Kesting
Hans Kesting

Reputation: 39255

Inspect the string that's created by that command: some words need spaces between them.

 SqlCommand cmd = new SqlCommand("IF NOT EXISTS(SELECT 1 from Raspunsuri where id_intrebare=2)" +
                " Insert INTO Raspunsuri VALUES(@raspuns,@cnp,@data,2,@ip,@idsesiune)" +
                " else" +
                " UPDATE Raspunsuri SET raspuns=@raspuns,cod_numeric_personal=@cnp,data_raspuns=@data,id_intrebare=2,ip_user=@ip,id_sesiune=@idsesiune WHERE id_intrebare=2", con);

Upvotes: 4

Vijay EK
Vijay EK

Reputation: 184

I think the blank spaces are missing between the "else" statement Also ensure that you have provided all the columns in the values part

Upvotes: 0

Pankaj
Pankaj

Reputation: 10095

You can try executing the query in SQL Server Management Studio window first. This will give you an easy way to debug the things

Upvotes: 1

Adriano Repetti
Adriano Repetti

Reputation: 67080

Why don't you use the MERGE command?

Upvotes: 1

Related Questions