In SQL Server you have stored procedures and table and scalar functions. Another feature that is convenient are common table expressions.
Functions you can use directly in SQL statements (SELECT
, INSERT
, UPDATE
, JOIN
), so they seamless to reuse.
Table function:
SELECT *
FROM myFunction(@UserID) as f
INNER JOIN users AS u ON f.UserID = u.ID
Scalar function you can put in SELECT
part of query.
SELECT u.ID, myFunction(u.ID)
FROM users as u
Common table expressions are nice for readability:
;WITH MyCTP AS
(
// complex SQL
)
SELECT *
FROM myTable INNER JOIN MyCTP ON...
You can have multiple CTEs before SELECT statement, but you can only use them in the statment above which they were declared.
Stored procedures
They are a bit of pain in the a$$, because you need to capture result into variables in order to use them in the calling stored procedure.
DECLARE @Input INT
DECLARE @Result INT
EXEC myStoredProcedure @Input, @Result OUT
If procedure outputs table, it gets even more complicated. You need to use cursor to capture result.