wasAsked.

Stored Procedure vs Function.

Capgemini · Full Stack Developer · technical

Published

Year not specified · SQL

Community answers

Posted by wasAsked editorial collection

Both are reusable programs stored in the database, but they have different purposes and rules (SQL Server). Stored procedure - Executed with EXEC; can perform any operation: SELECT, INSERT, UPDATE, DELETE, DDL, transactions, and calling other procedures. - Can return zero, one or many result sets, output parameters, and an integer return code. - Supports TRY/CATCH error handling and explicit transactions. - Cannot be used inside a SELECT statement. - Typical use: business operations and data modifications (PlaceOrder, ProcessPayroll), batch jobs and reports. CREATE PROCEDURE dbo.usp_CreateOrder @CustomerId INT, @Total DECIMAL(18,2), @OrderId INT OUTPUT AS BEGIN SET NOCOUNT ON; INSERT INTO Orders (CustomerId, Total) VALUES (@CustomerId, @Total); SET @OrderId = SCOPE_IDENTITY(); END; Function (user-defined function) - Must return a value: a scalar value or a table (table-valued function). - Can be used inside queries: in SELECT, WHERE, JOIN (table-valued functions in FROM or with APPLY). - Cannot modify database state (no INSERT, UPDATE or DELETE on permanent tables), cannot use explicit transactions or TRY/CATCH, and cannot call stored procedures. - Typical use: calculations and reusable query logic. CREATE FUNCTION dbo.fn_GetOrderTotalWithTax (@Total DECIMAL(18,2)) RETURNS DECIMAL(18,2) AS BEGIN RETURN @Total * 1.18; END; SELECT OrderId, dbo.fn_GetOrderTotalWithTax(Total) FROM Orders; Summary of differences - Return: procedures optionally return values and result sets; functions must return a scalar or table. - Use in SELECT: procedures no; functions yes. - Data modification: procedures yes; functions no. - Transactions and TRY/CATCH: procedures yes; functions no. - Calling each other: procedures can call functions; functions cannot call procedures. - Parameters: procedures support output parameters; functions support only input parameters. Performance notes - Scalar UDFs used per row can be slow; SQL Server 2019 introduced scalar UDF inlining to help, but not every function qualifies. - Inline table-valued functions (a single SELECT) are expanded into the calling query like views with parameters, and perform much better than multi-statement table-valued functions. - Stored procedures benefit from plan caching but can suffer from parameter sniffing; use OPTION (RECOMPILE) or other techniques when needed.

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics