Returning a value from a Stored proc as an Output parameter vs a SELECT statement
A very silly example, but if I need to get the max order ID out of the orders table and I have two options 开发者_开发知识库(I know there are more, but I'm just interested in these two). I'm interested in knowing which ends up being less overhead.
A first one that simply selects the value out:
CREATE PROCEDURE GetLastOrderID
AS
SELECT Max(OrderID) FROM Orders
and then corresponding C# code to create a SQLCommand to execute the proc, call .ExecuteScalar, and cast the value to an int.
A second one that passes the value out as an output parameter
CREATE PROCEDURE GetLastOrderID (@MaxOrderID INT OUTPUT)
AS
SET @MaxOrderId = Max(OrderID) FROM Orders
and then corresponding C# code to create a SQLCommand to execute the proc, add an output parameter of type int, then call .ExecuteNonQuery, and finally get the value of the output parameter.
Is there any real benefit of one over the other? My gut feel is that the first option will take more time/resources because there's no explicit types given, but I'd love to know if there's a definitive answer out there. (or at least one that beats my "gut feel" in terms of authority)
No.
The overhead of which you are referring to is neglible compared to actually running the TSQL MAX() statement on anything except a trivial number of rows.
Use the form that is most understandable and most maintainable.
Worry about performance when you have identified a performance problem.
Output parameters are more light weight.
精彩评论