User-specific SQL If statement

So, I have 2 users, one of which is called admin, the other is admin2.

I wrote an SQL query in which I want to increase the achievement of a specific account, in my case only for admin, but contrary to this, the same achievement for the user is admin2also affected. What am I doing wrong?

DECLARE @Achievement1 INT

SELECT @Achievement1 = Achievement1
FROM [dbo].[Achievement]
WHERE [dbo].[Achievement].UserID = (SELECT [AccountID]
                                    FROM [dbo].[Account]
                                    WHERE [Username] = 'Admin')

IF (@Achievement1 < 100)
    UPDATE [dbo].[Achievement]
    SET [Achievement1] += 2
ELSE
    UPDATE [dbo].[Achievement]
    SET [Achievement1] += 0
+4
source share
2 answers

Your code updates all lines in Achievementthe condition. This is not just updating the corresponding line.

Your logic is rather confusing. I think you can just do this:

UPDATE a
    SET Achievement1 += 2
    FROM dbo.Achievement a
    WHERE a.Achievement1 < 100 AND
          a.UserId = (SELECT ac.AccountId
                      FROM dbo.Account ac
                      WHERE ac.UserName = 'admin' 
                     );

. UserId , AccountId . , ?

+6

, :

UPDATE a1
SET a1.[Achievement1] = CASE WHEN a1.Achievement1 < 100 THEN a1.[Achievement1] + 2  
                          ELSE a1.[Achievement1] END
FROM [dbo].[Achievement] AS a1
INNER JOIN [dbo].[Account] AS a2 ON a1.UserID = a2.[AccountID]
WHERE a2.UserName = 'admin';
+2

Source: https://habr.com/ru/post/1691312/


All Articles