for some SQL queries I know the expected number of rows that must be affected by UPDATE, DELETE or INSERT statements. It could be a number such as 1 or a range such as 0-1 or 1-2 etc.
How can I enforce that this is the number of affected rows and that otherwise an exception is thrown?
Also, can I limit the number of rows affected for UPDATE/DELETE/INSERT to say 1 row and otherwise get an exception?
4条答案
按热度按时间zsbz8rwp1#
You can use TOP in insert, update and delete to enforce the number of rows affected. There is no exception thrown with this.
If you want exception you can use
@@ROWCOUNT
in a transaction.ztyzrc3y2#
For UPDATE, INSERT, and DELETE statements, ExecuteNonQuery returns the number of rows affected by the command.
I suggest you wrap the call in a transaction and if the result is not as expected rollback the transaction and throw an exception.
You can also use @@ROWCOUNT to do the same inside the query.
pw136qt23#
Use @@ROWCOUNTdirectly after your statement. If not equal to what you want, use RAISERROR .
One small warning however, RAISERROR has a severity parameter. Use a number between 11 and 19. Lower then 11 is considered a warning. Higher than 19 can only be done by sysadmins, is a fatal error and terminates your connection.
tf7tbtn24#
I think at the query level, the thing to use is either @@ROWCOUNT within the procedure or similar outside, but you need to use transactions.
If you want to go a little lower in the database (since the above technique would only protect queries designed to use such a framework), then you can use triggers on tables and get a count of the INSERTED or DELETED pseudo-tables and use RAISERRROR to raise an appropriate error.