I am trying to update a specific column inside a SQL Server table where the Id of the row in which the column is, is the highest Id currently inside the table. The error message says that there is a syntax error near "ORDER" inside my query
I have done some research already on whether it is possible to use a SQL UPDATE
statement followed by an ORDER BY
statement, so that I update a specific column in the row with the highest Id in the table. I have found out that it is possible and what the syntax is, yet I still get an error when I follow the guidelines I have found and use the syntax.
My connection code that is linked to a button event:
SqlConnection newconnection = new SqlConnection(ConfigurationManager.ConnectionStrings["derpection"].ConnectionString);
string sql01 = "UPDATE Messages SET Besked = 'test' ORDER BY Id";
SqlCommand hmm01 = new SqlCommand(sql01, newconnection);
newconnection.Open();
hmm01.ExecuteNonQuery();
newconnection.Close();
My table:
CREATE TABLE [dbo].[Messages]
(
[Id] INT IDENTITY (1, 1) NOT NULL,
[Besked] VARCHAR(50) NULL,
[BrugerID] INT NOT NULL,
[Username] VARCHAR (50) NOT NULL,
PRIMARY KEY CLUSTERED ([Id] ASC),
CONSTRAINT [FK_Users]
FOREIGN KEY ([BrugerID]) REFERENCES [dbo].[Users] ([Id])
);
I expect it to update the row with the highest Id, but the result is an error message. Even though the syntax should be right.
[ WITH <common_table_expression> [...n] ]
UPDATE
[ TOP ( expression ) [ PERCENT ] ]
{ { table_alias | <object> | rowset_function_limited
[ WITH ( <Table_Hint_Limited> [ ...n ] ) ]
}
| @table_variable
}
SET
{ column_name = { expression | DEFAULT | NULL }
| { udt_column_name.{ { property_name = expression
| field_name = expression }
| method_name ( argument [ ,...n ] )
}
}
| column_name { .WRITE ( expression , @Offset , @Length ) }
| @variable = expression
| @variable = column = expression
| column_name { += | -= | *= | /= | %= | &= | ^= | |= } expression
| @variable { += | -= | *= | /= | %= | &= | ^= | |= } expression
| @variable = column { += | -= | *= | /= | %= | &= | ^= | |= } expression
} [ ,...n ]
[ <OUTPUT Clause> ]
[ FROM{ <table_source> } [ ,...n ] ]
[ WHERE { <search_condition>
| { [ CURRENT OF
{ { [ GLOBAL ] cursor_name }
| cursor_variable_name
}
]
}
}
]
[ OPTION ( <query_hint> [ ,...n ] ) ]
[ ; ]
<object> ::=
{
[ server_name . database_name . schema_name .
| database_name .[ schema_name ] .
| schema_name .
]
table_or_view_name}
This is the full valid syntax tree for update statement in Sql Server and Update .. Order By
is not one of them.
You can however use a sub query to do what you want
UPDATE Messages SET Besked = 'test'
WHERE Id IN (SELECT TOP 1 Id FROM Messages ORDER BY Id DESC)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.