command.Parameters.AddWithValue("@ordreid", ("MAX(ordreid)+1 FROM ordreid"));
The method name AddWithValue
hints at the reason why this won't work: Parameters contain data, that is: values. They cannot represent a part of a SQL statement.
Your intention appears to be that @ordreid
should be replaced with that piece of SQL. If this is so, then there's no reason to even have a parameter. Simply perform the substitution manually and change the CommandText
:
command.CommandText = @"INSERT INTO ordreid (ordrenr, ordreid)
VALUES (@ordrenr, (SELECT MAX(ordreid)+1 FROM ordreid));";
Note that I changed four things (apart from spreading the command text across two lines, for legibility's sake, using C#'s @"…"
string syntax). Only the first two points are crucial:
I moved the MAX(…)
SQL directly into your CommandText
. This makes the (invalid) @ordreid
parameter obsolete.
To determine the value of MAX(ordreid) FROM ordreid
, you need a sub-query; thus the added SELECT
before MAX
. Otherwise, the syntax wouldn't be valid.
I replaced your SELECT
with a VALUES
table value constructor. (Otherwise, because of the previous point, we'd have two SELECT
s very close to each other, which would look somewhat confusing.)
I added a ;
at the end of your query. Current versions of SQL Server don't yet require such a statement terminator, but Microsoft has hinted that they might become compulsory in future versions of T-SQL. I therefore believe that it's a good habit to get into now.
That all being said, you should probably turn the ordreid
column into an IDENTITY
column and let SQL Server choose the value to be inserted (making the SELECT MAX(…)
business obsolete). Otherwise, if two processes or threads execute the same INSERT
command at the same time, you might end up with several rows having the same value for ordreid
.