0

How can I insert parameter with value from database. I have some field and I should insert value from this database + 1 (with plus one)

For example

myCommand.CommandText =
            "INSERT INTO GAMES (GAME_NR, GAME_PLAYER_ID, GAME_NRONTABLE, GAME_ROLE_ID) " &
            " VALUES (@game_nr, @game_player_id, @game_nrontable, @game_role_id)"

'Example
myCommand.Parameters.Add("@game_nr", SqlDbType.Int).Value = **"(SELECT MAX(GAME_NR) FROM GAMES)" + 1**

2 Answers 2

2

You don't. You make GAME_NR and auto-incremented primary key:

create table games (
    game_nr int auto_increment primary key,
    . . .
);

Then you do the insert as:

INSERT INTO GAMES (GAME_PLAYER_ID, GAME_NRONTABLE, GAME_ROLE_ID)
    VALUES (@game_player_id, @game_nrontable, @game_role_id);

Let the database do the work.

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

Comments

0

You don't need the parameter, you can try following code.

myCommand.CommandText =
            "INSERT INTO GAMES (GAME_NR, GAME_PLAYER_ID, GAME_NRONTABLE, GAME_ROLE_ID) " &
            " VALUES ((SELECT MAX(GAME_NR) + 1 FROM GAMES), @game_player_id, @game_nrontable, @game_role_id)"

But it looks like a primary key of the table. If Game_Nr is pr, You should use auto-inc. identity, then you don't need this param.

It will be.

myCommand.CommandText =
                "INSERT INTO GAMES (GAME_PLAYER_ID, GAME_NRONTABLE, GAME_ROLE_ID) " &
                " VALUES (@game_player_id, @game_nrontable, @game_role_id)"

3 Comments

How would that behave in a multi-user environment? For example, current MAX(GAME_NR) = 100. Then you and me run INSERT you suggest, and for both of us MAX + 1 = 101. If GAME_NR was a primary key ... hm?
thank Littlefoot for warning me, I will edit my answer. But I don't agree with you. I think, there will first execute generate 101 then 102.
Until user COMMITs changes (i.e. that INSERT statement), everyone else, who selects MAX(GAME_NR) would see the old value. So, if there were 20 users who did INSERT INTO with MAX(GAME_NR) + 1, all of them would want to insert 101, but only the first one who commits would succeed. Everyone else's attempt would fail because of primary key violation. That's why, generally speaking, MAX + 1 is a bad idea. Though, if AUTOCOMMIT is enabled, database would commit itself so those problems would, probably, be avoided. Personally, I prefer choosing when to commit.

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.