Middle
Erinevused protseduuri ja funktsiooni vahel
sobes.tech AI
Vastus AI-lt
Procedures and functions are subprograms in databases and programming, but there are key differences:
- Function always returns a value and can be used in expressions, for example, in SELECT.
- Procedure can perform actions (for example, modify data), but is not required to return a value directly.
Example in SQL (PL/pgSQL):
-- Function returns the sum of two numbers
CREATE FUNCTION add_numbers(a INT, b INT) RETURNS INT AS $$
BEGIN
RETURN a + b;
END;
$$ LANGUAGE plpgsql;
-- Procedure inserts a record into a table
CREATE PROCEDURE insert_user(name TEXT) AS $$
BEGIN
INSERT INTO users(username) VALUES (name);
END;
$$ LANGUAGE plpgsql;
Functions are typically used for calculations and return a result, procedures — for executing operations, often with side effects.