0
string searched = TextBox1.Text; // for example, text is 4477

...

sorgu.CommandText = "IF EXISTS(SELECT * FROM [Pins] WHERE Pin =' " + searched.ToString() + " ') BEGIN UPDATE [Pins] SET SAY= SAY+1, Pin = ' " + searched.ToString() + " ' END ELSE BEGIN INSERT INTO Pins(SAY,Pin) VALUES (+1,' " + searched.ToString() + " ') END";

...

I am using SAY for counting the number of searches.

This code is changing all records on column (Pins) to searched text.

Where/What is my fault?

2
  • 2
    You don't have a where clause on your update statement. The bigger problem is that this is a textbook example of sql injection. You need to parameterize your queries before bobby tables comes for a visit. bobby-tables.com Commented Feb 11, 2016 at 15:02
  • I would move this to a stored procedure so you have better control over what is happening and you can debug/maintain it without having to parse this big nasty string into something legible. Commented Feb 11, 2016 at 15:04

3 Answers 3

1

In pseudo code, you're saying

IF EXISTS(SELECT Statement) UPDATE ALL ROWS

The correct way to do this with EXISTS is

UPDATE TABLE
WHERE EXISTS(Correlated SELECT Statement)
Sign up to request clarification or add additional context in comments.

Comments

1

You need to have a where to not update all records. This would fix it.... but is a horrible query.

IF EXISTS(SELECT * FROM [Pins] WHERE Pin = 'searched.ToString()')
BEGIN 
    UPDATE [Pins] SET SAY = SAY + 1
    WHERE [Pin] = 'searched.ToString() '
END 
ELSE 
BEGIN 
    INSERT INTO Pins(SAY, Pin) VALUES (1, 'searched.ToString()') 
END

Comments

0

You missed the WHERE clause.

I would also prefer using Parameters instead of string concatenated query (which makes your code open to SQL injection attacks)

string searched = TextBox1.Text; // for example, text is 4477

sorgu.CommandText = "IF EXISTS(SELECT * FROM [Pins] WHERE Pin = @searched) BEGIN UPDATE [Pins] SET SAY=SAY+1 WHERE Pin = @searched END ELSE BEGIN INSERT INTO Pins(SAY,Pin) VALUES (1, @searched) END";
sorgu.Parameters.AddWithValue("@searched", TextBox1.Text);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.