What stored procedures, functions, triggers and views are
A relational database stores more than tables. Many applications also keep part of their logic inside the database, as named objects that the database stores, compiles and runs itself:
- Stored procedure: a named block of code that the application calls, for example
EXEC dbo.CreateOrderorCALL create_order(…). It can read and change data, run several statements in one transaction, return output parameters and, depending on the engine, result sets. - Function: code that returns a value or a table and can be used inside a query, such as
SELECT dbo.NetPrice(Price) FROM Products. What a function may do differs per engine: in SQL Server it cannot change data, in PostgreSQL it can. - Trigger: code that the database runs automatically when rows are inserted, updated or deleted, for example to keep an audit trail or enforce a rule. Nobody calls it explicitly, which makes it easy to overlook.
- View: a stored query that behaves like a table. A view contains no procedural code, but it does use the SQL dialect of the engine: functions, date arithmetic,
TOPorLIMIT. - Package (Oracle): a group of procedures, functions, types and variables with a public specification and a private body.
Applications use them for several reasons: one round trip instead of many, rules that apply to every application that touches the data, permissions granted on a procedure instead of on tables, and a plan that is compiled once and reused. In older client-server applications, the database code often contains most of the business logic.
The code runs inside the database server, in the session and usually in the transaction of the caller. It reaches the data directly, without a network in between, and the engine decides how each statement inside it is executed. That is also why it is tied to one engine: it depends on that engine's language, built-in functions, error handling and transaction behaviour.
One idea, four dialects
The SQL standard describes procedural code (SQL/PSM), but every engine has its own language. The basic statements SELECT, INSERT, UPDATE and DELETE look much the same everywhere; variables, control flow, error handling, transactions and built-in functions do not.
- T-SQL (SQL Server, Azure SQL): variables start with
@, a procedure returns result sets by simply running aSELECT, and errors are caught withTRY … CATCH. - PL/pgSQL (PostgreSQL): modelled on Oracle's PL/SQL, with a
DECLAREsection,EXCEPTIONblocks and the body as a string between$$quotes. PostgreSQL also accepts functions in plain SQL and in other languages such as PL/Python. - MySQL and MariaDB: a dialect close to SQL/PSM, with
DECLARE … HANDLERto catch errors andSIGNALto raise them. MariaDB also has an Oracle compatibility mode that accepts part of PL/SQL. - PL/SQL (Oracle): a full programming language with packages, collections, record types, bulk operations and autonomous transactions.
Rewriting therefore means more than translating keywords. Two pieces of code that look the same can behave differently, for example with NULL values, empty strings, an error halfway through a transaction or text comparisons.
How to rewrite: a method in six steps
Rewriting database code is a small software project. It goes best with a fixed order of work per object, and with the old system still available to compare against.
- 1. Inventory. List every procedure, function, trigger, view and package, with its size and the features it uses. Find out which objects are still called: in an older database part of the code is often no longer used and does not need converting at all. Query Store,
sys.dm_exec_procedure_stats,pg_stat_user_functions, the Performance Schema or AWR show what actually runs. - 2. Classify. Sort the objects into easy, medium and hard (see below) and decide per object: convert, move to the application, or drop. Convert dependencies first: tables and views before the procedures that use them, called procedures before their callers.
- 3. Convert. Let a tool do the mechanical part, then rework by hand what the tool marks as not converted or converts literally but wrongly. Keep the structure of the original where possible, so that old and new can be compared side by side; improving the code is a separate step.
- 4. Compile. Create the objects on the target. PostgreSQL checks the syntax of a PL/pgSQL function when it is created, but resolves table and column names only when the code runs; the
plpgsql_checkextension finds many of those errors in advance. - 5. Test with the same input. Run each object on old and new with the same parameters and the same data, and compare results, output parameters, changed rows and errors. More on this below.
- 6. Check performance. Code that is fast on one engine can be slow on another, because of different plans, row-by-row processing or missing indexes. Measure the heaviest procedures with production-like volumes before the switch-over.
Tools that help, and what they cannot do
Conversion tools save a lot of typing and give a useful first estimate. They are dependable for tables, indexes and simple code, less so for procedural logic.
- AWS DMS Schema Conversion and the older AWS Schema Conversion Tool (SCT): convert schemas and code from SQL Server, Oracle and other sources to PostgreSQL, MySQL and other targets, with a report of what could not be converted.
- SQL Server Migration Assistant (SSMA): Microsoft's free tool to convert Oracle, MySQL, Db2, SAP ASE and Access to SQL Server and Azure SQL, including procedures and triggers.
- ora2pg: open-source tool from Oracle and MySQL to PostgreSQL. It converts tables, data and PL/SQL to PL/pgSQL and produces a migration report with an effort estimate.
- Babelfish Compass: analyses T-SQL scripts and reports which of the features used are supported by Babelfish for Aurora PostgreSQL.
- pgloader and sqlserver2pgsql: move tables and data to PostgreSQL. They do not convert procedural code.
What no tool does reliably is decide whether the behaviour is still the same. Tools convert syntax; they do not know that the application relies on case-insensitive comparisons, on an empty string being NULL, on the order in which a procedure returns rows, or on an error log that survives a rollback. Dynamic SQL is converted as a string, so the SQL inside it stays in the old dialect. Calls to the operating system, mail, files, web services, linked servers or CLR assemblies have no equivalent in the target and need a design decision.
Some tools now add AI-assisted conversion. That speeds up the first draft, but the same rule applies: the result is only as good as the tests that compare it with the original. Expect to review every converted object and to rewrite the complex ones largely by hand.
Construct by construct: T-SQL, PL/pgSQL, MySQL and PL/SQL
The table maps the constructs that appear in almost every procedure. It is a starting point, not a complete reference: the behaviour can differ in the details, as the notes show.
| Construct | T-SQL (SQL Server) | PL/pgSQL (PostgreSQL) | MySQL / MariaDB | PL/SQL (Oracle) |
|---|---|---|---|---|
| Declare a variable | DECLARE @n int = 0; | DECLARE n integer := 0; (in the DECLARE section) | DECLARE n INT DEFAULT 0; (at the start of a BEGIN … END block) | n NUMBER := 0; (in the declaration section) |
| Assign a value | SET @n = 1; · SELECT @n = col FROM … | n := 1; · SELECT col INTO n FROM … | SET n = 1; · SELECT col INTO n FROM … | n := 1; · SELECT col INTO n FROM … (no row raises NO_DATA_FOUND) |
| Conditions and loops | IF … BEGIN … END ELSE … · WHILE … BEGIN … END | IF … THEN … ELSIF … END IF; · LOOP, WHILE, FOR i IN 1..10 | IF … THEN … ELSEIF … END IF; · WHILE … DO, REPEAT, LOOP | IF … THEN … ELSIF … END IF; · LOOP, WHILE, FOR i IN 1..10 |
| Catch errors | BEGIN TRY … END TRY BEGIN CATCH … END CATCH | BEGIN … EXCEPTION WHEN … THEN … END; | DECLARE EXIT HANDLER FOR SQLEXCEPTION … | BEGIN … EXCEPTION WHEN … THEN … END; |
| Error details | ERROR_MESSAGE(), ERROR_NUMBER() | SQLERRM, SQLSTATE, GET STACKED DIAGNOSTICS | GET DIAGNOSTICS CONDITION 1 v = MESSAGE_TEXT | SQLERRM, SQLCODE |
| Raise an error | THROW 50001, 'msg', 1; · RAISERROR('msg', 16, 1); | RAISE EXCEPTION 'msg %', v; | SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'msg'; | RAISE_APPLICATION_ERROR(-20001, 'msg'); |
| Return a result set | a SELECT in the procedure; the client receives every result set | a function with RETURNS TABLE (…) or SETOF and RETURN QUERY, or a procedure with an INOUT refcursor | a SELECT in the procedure; several result sets are possible | an OUT SYS_REFCURSOR parameter, or DBMS_SQL.RETURN_RESULT |
| Output parameter | @id int OUTPUT | OUT id integer, INOUT (procedures accept OUT from PostgreSQL 14) | OUT id INT, INOUT | id OUT NUMBER, IN OUT |
| Temporary data | #temp table (dropped when the procedure ends), @t TABLE variable | CREATE TEMP TABLE (lives for the session; ON COMMIT DROP), arrays | CREATE TEMPORARY TABLE (lives for the session) | global temporary table (created once), private temporary table (18c+), collections |
| Last generated key | SCOPE_IDENTITY(), OUTPUT inserted.id | INSERT … RETURNING id INTO v | LAST_INSERT_ID() (MariaDB 10.5+: also INSERT … RETURNING) | INSERT … RETURNING id INTO v |
| First n rows | SELECT TOP (10) … | LIMIT 10, FETCH FIRST 10 ROWS ONLY | LIMIT 10 | FETCH FIRST 10 ROWS ONLY (12c+), ROWNUM |
| Concatenate text | 'a' + 'b' (NULL if one part is NULL), CONCAT() (ignores NULL) | 'a' || 'b' (NULL if one part is NULL), concat() (ignores NULL) | CONCAT('a', 'b') (NULL if one part is NULL); || means OR unless PIPES_AS_CONCAT is set | 'a' || 'b' (NULL counts as an empty string) |
| Replace NULL | ISNULL(x, 0), COALESCE(x, 0) | COALESCE(x, 0) | IFNULL(x, 0), COALESCE(x, 0) | NVL(x, 0), COALESCE(x, 0) |
| Current date and time | GETDATE(), SYSDATETIME() | now(), CURRENT_TIMESTAMP (start of the transaction); clock_timestamp() (actual time) | NOW() (start of the statement); SYSDATE() (actual time) | SYSDATE (type DATE, to the second), SYSTIMESTAMP |
| Dynamic SQL | EXEC sp_executesql @sql, N'@id int', @id = @id; | EXECUTE format('DELETE FROM %I WHERE id = $1', t) USING v; | PREPARE s FROM @sql; EXECUTE s USING @id; (not in functions or triggers) | EXECUTE IMMEDIATE v_sql USING v; |
| Cursor loop | DECLARE c CURSOR FOR …, FETCH NEXT FROM c INTO …, WHILE @@FETCH_STATUS = 0 | FOR r IN SELECT … LOOP … END LOOP; | DECLARE c CURSOR FOR … + DECLARE CONTINUE HANDLER FOR NOT FOUND | FOR r IN (SELECT …) LOOP … END LOOP; |
| Rows affected | @@ROWCOUNT | GET DIAGNOSTICS n = ROW_COUNT;, FOUND | ROW_COUNT() | SQL%ROWCOUNT |
| Transactions in the code | BEGIN TRAN … COMMIT; nesting only raises @@TRANCOUNT | COMMIT and ROLLBACK only in a procedure started with CALL outside an explicit transaction; not in functions or in a block with EXCEPTION | START TRANSACTION … COMMIT in procedures, not in functions or triggers; START TRANSACTION first commits an open transaction | COMMIT is allowed anywhere and also commits the caller's work; PRAGMA AUTONOMOUS_TRANSACTION for an independent transaction |
| Upsert | MERGE | INSERT … ON CONFLICT … DO UPDATE; MERGE (from PostgreSQL 15) | INSERT … ON DUPLICATE KEY UPDATE | MERGE |
| Group related code | schemas | schemas; no package state | none (MariaDB: packages in Oracle mode) | PACKAGE and PACKAGE BODY, with variables that keep their value per session |
Two differences cause the most work. First, result sets: in SQL Server and MySQL a procedure returns rows by running a SELECT; in PostgreSQL and Oracle it returns a cursor or becomes a function that returns a table, and the application code that reads the result changes with it. Second, transactions and errors: where a transaction starts and ends, and what remains after an error, differs per engine.
Worked example: one procedure in four dialects
A typical procedure from an order system: it checks the input, looks up the customer's current discount, inserts an order, updates the customer, returns the new order number and logs errors. First the original in T-SQL, then a rewrite for each of the other engines.
CREATE PROCEDURE dbo.CreateOrder
@CustomerId int,
@Amount decimal(12,2),
@OrderId int OUTPUT
AS
BEGIN
SET NOCOUNT ON;
DECLARE @Discount decimal(5,2);
BEGIN TRY
IF @Amount <= 0
THROW 50001, 'Amount must be positive', 1;
BEGIN TRANSACTION;
SELECT TOP (1) @Discount = DiscountPct
FROM dbo.Contracts
WHERE CustomerId = @CustomerId AND ValidFrom <= GETDATE()
ORDER BY ValidFrom DESC;
INSERT INTO dbo.Orders (CustomerId, Amount, CreatedAt)
VALUES (@CustomerId, @Amount * (1 - ISNULL(@Discount, 0) / 100), GETDATE());
SET @OrderId = SCOPE_IDENTITY();
UPDATE dbo.Customers SET LastOrderAt = GETDATE()
WHERE CustomerId = @CustomerId;
COMMIT TRANSACTION;
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION;
INSERT INTO dbo.ErrorLog (ProcName, Message, LoggedAt)
VALUES ('CreateOrder', ERROR_MESSAGE(), GETDATE());
THROW;
END CATCH
END;CREATE OR REPLACE PROCEDURE create_order(
p_customer_id integer,
p_amount numeric,
OUT p_order_id integer)
LANGUAGE plpgsql
AS $$
DECLARE
v_discount numeric(5,2);
BEGIN
IF p_amount <= 0 THEN
RAISE EXCEPTION 'Amount must be positive';
END IF;
SELECT discount_pct INTO v_discount
FROM contracts
WHERE customer_id = p_customer_id AND valid_from <= now()
ORDER BY valid_from DESC
LIMIT 1;
INSERT INTO orders (customer_id, amount, created_at)
VALUES (p_customer_id, p_amount * (1 - COALESCE(v_discount, 0) / 100), now())
RETURNING order_id INTO p_order_id;
UPDATE customers SET last_order_at = now()
WHERE customer_id = p_customer_id;
EXCEPTION
WHEN OTHERS THEN
-- no autonomous transactions: a row inserted into error_log here
-- would be rolled back by the RAISE below
RAISE WARNING 'create_order failed: %', SQLERRM;
RAISE;
END;
$$;
-- CALL create_order(42, 100.00, NULL);DELIMITER //
CREATE PROCEDURE create_order(
IN p_customer_id INT,
IN p_amount DECIMAL(12,2),
OUT p_order_id INT)
BEGIN
DECLARE v_discount DECIMAL(5,2);
DECLARE v_message TEXT;
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
GET DIAGNOSTICS CONDITION 1 v_message = MESSAGE_TEXT;
ROLLBACK;
INSERT INTO error_log (proc_name, message, logged_at)
VALUES ('create_order', v_message, NOW());
RESIGNAL;
END;
IF p_amount <= 0 THEN
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Amount must be positive';
END IF;
START TRANSACTION;
SELECT discount_pct INTO v_discount
FROM contracts
WHERE customer_id = p_customer_id AND valid_from <= NOW()
ORDER BY valid_from DESC
LIMIT 1;
INSERT INTO orders (customer_id, amount, created_at)
VALUES (p_customer_id, p_amount * (1 - IFNULL(v_discount, 0) / 100), NOW());
SET p_order_id = LAST_INSERT_ID();
UPDATE customers SET last_order_at = NOW() WHERE customer_id = p_customer_id;
COMMIT;
END //
DELIMITER ;CREATE OR REPLACE PROCEDURE create_order (
p_customer_id IN NUMBER,
p_amount IN NUMBER,
p_order_id OUT NUMBER
) AS
v_discount NUMBER(5,2);
BEGIN
SAVEPOINT create_order_start;
IF p_amount <= 0 THEN
RAISE_APPLICATION_ERROR(-20001, 'Amount must be positive');
END IF;
BEGIN
SELECT discount_pct INTO v_discount
FROM contracts
WHERE customer_id = p_customer_id AND valid_from <= SYSDATE
ORDER BY valid_from DESC
FETCH FIRST 1 ROW ONLY;
EXCEPTION
WHEN NO_DATA_FOUND THEN v_discount := 0;
END;
INSERT INTO orders (customer_id, amount, created_at)
VALUES (p_customer_id, p_amount * (1 - NVL(v_discount, 0) / 100), SYSDATE)
RETURNING order_id INTO p_order_id;
UPDATE customers SET last_order_at = SYSDATE
WHERE customer_id = p_customer_id;
EXCEPTION
WHEN OTHERS THEN
log_error('create_order', SQLERRM); -- PRAGMA AUTONOMOUS_TRANSACTION
ROLLBACK TO create_order_start;
RAISE;
END;
/- TOP (1) becomes
LIMIT 1orFETCH FIRST 1 ROW ONLY. If no contract exists, SQL Server, PostgreSQL and MySQL leave the variable NULL; Oracle raisesNO_DATA_FOUND, hence the nested block. - SCOPE_IDENTITY() becomes
RETURNING … INTOin PostgreSQL and Oracle, andLAST_INSERT_ID()in MySQL. - GETDATE() becomes
now(),NOW()orSYSDATE. In PostgreSQLnow()returns the start of the transaction, so every statement in the procedure gets exactly the same time. - The error log is the real difference. In SQL Server the log row is written after the rollback and is kept. In PostgreSQL the
RAISEundoes the whole call, including anything the handler wrote, and there are no autonomous transactions: the error has to be logged by the application or over a separate connection, for example with the dblink extension. Oracle needs a logging procedure withPRAGMA AUTONOMOUS_TRANSACTION. MySQL behaves like SQL Server here, as long as autocommit is on. - Transactions: the T-SQL procedure also works inside a transaction of the caller. The PostgreSQL and Oracle versions leave the commit to the caller; the Oracle version uses a savepoint to undo only its own work. In MySQL,
START TRANSACTIONsilently commits a transaction the caller already had open, so this version assumes there is none. - The call changes too:
EXEC dbo.CreateOrder 42, 100.00, @id OUTPUTbecomesCALL create_order(42, 100.00, NULL)in PostgreSQL (the output parameter comes back as a row),CALL create_order(42, 100.00, @id)in MySQL, and a PL/SQL block or driver call in Oracle.
Triggers: statement-level versus row-level
Triggers are where a literal translation most often goes wrong, because SQL Server fires a trigger once per statement, MySQL once per row, and PostgreSQL and Oracle can do both.
In SQL Server, an UPDATE that changes 500 rows fires the trigger once. The trigger sees all changed rows in two pseudo-tables, deleted (the old values) and inserted (the new values), and should process them as a set. In MySQL, the same update fires a FOR EACH ROW trigger 500 times, each time with one row in OLD and NEW. PostgreSQL supports both: FOR EACH ROW with OLD and NEW, or FOR EACH STATEMENT with transition tables declared with REFERENCING OLD TABLE … NEW TABLE, the closest equivalent of deleted and inserted. In PostgreSQL the trigger code is a separate function that returns trigger.
CREATE TRIGGER dbo.trg_Products_PriceAudit
ON dbo.Products
AFTER UPDATE
AS
BEGIN
SET NOCOUNT ON;
-- fires once per statement; inserted and deleted hold all changed rows
INSERT INTO dbo.PriceHistory (ProductId, OldPrice, NewPrice, ChangedAt)
SELECT d.ProductId, d.Price, i.Price, GETDATE()
FROM inserted AS i
JOIN deleted AS d ON d.ProductId = i.ProductId
WHERE i.Price <> d.Price;
END;CREATE OR REPLACE FUNCTION products_price_audit()
RETURNS trigger
LANGUAGE plpgsql
AS $$
BEGIN
INSERT INTO price_history (product_id, old_price, new_price, changed_at)
VALUES (OLD.product_id, OLD.price, NEW.price, now());
RETURN NULL; -- ignored for AFTER triggers
END;
$$;
CREATE TRIGGER trg_products_price_audit
AFTER UPDATE OF price ON products
FOR EACH ROW
WHEN (OLD.price <> NEW.price)
EXECUTE FUNCTION products_price_audit();CREATE OR REPLACE FUNCTION products_price_audit_stmt()
RETURNS trigger
LANGUAGE plpgsql
AS $$
BEGIN
INSERT INTO price_history (product_id, old_price, new_price, changed_at)
SELECT o.product_id, o.price, n.price, now()
FROM new_rows AS n
JOIN old_rows AS o ON o.product_id = n.product_id
WHERE n.price <> o.price;
RETURN NULL;
END;
$$;
CREATE TRIGGER trg_products_price_audit_stmt
AFTER UPDATE ON products
REFERENCING OLD TABLE AS old_rows NEW TABLE AS new_rows
FOR EACH STATEMENT
EXECUTE FUNCTION products_price_audit_stmt();DELIMITER //
CREATE TRIGGER trg_products_price_audit
AFTER UPDATE ON products
FOR EACH ROW
BEGIN
-- fires once per changed row
IF NEW.price <> OLD.price THEN
INSERT INTO price_history (product_id, old_price, new_price, changed_at)
VALUES (OLD.product_id, OLD.price, NEW.price, NOW());
END IF;
END //
DELIMITER ;Both PostgreSQL versions give the same result. The row-level version is simpler and is what most tools generate; the statement-level version keeps the set-based logic of the original and is faster for large updates.
Watch out for SQL Server triggers written as if only one row changes, such as SELECT @Id = ProductId FROM inserted: they silently handle only one row of a multi-row update. A row-level rewrite happens to fix that bug, which also means old and new can give different results, so compare them deliberately. Oracle has row-level triggers with :OLD and :NEW, statement-level triggers and compound triggers that combine both. SQL Server also allows INSTEAD OF triggers on tables; PostgreSQL and Oracle only on views, and MySQL has none.
The classic traps
Most problems after a conversion are not syntax errors, which the compiler finds, but differences in behaviour that only show up with real data:
- Case sensitivity: SQL Server and MySQL usually compare text case-insensitively (
'abc' = 'ABC'is true); PostgreSQL and Oracle compare case-sensitively by default. Searches, joins, unique constraints andGROUP BYcan return different rows. In PostgreSQL a nondeterministic ICU collation or the citext type restores the old behaviour where needed. - Empty string and NULL: Oracle treats
''as NULL; the other engines do not.WHERE col = ''never matches in Oracle, and code that leaves Oracle suddenly meets empty strings that used to be NULL. - Implicit conversions: SQL Server and MySQL quietly convert between text, numbers and dates; PostgreSQL refuses to compare a text column with a number without an explicit cast. Division differs too:
5 / 2is 2 in SQL Server and PostgreSQL, but 2.5 in MySQL and Oracle. - Dates and times:
datetimein SQL Server is rounded to 1/300 of a second, an OracleDATEcontains a time, PostgreSQLnow()stays the same for the whole transaction, and date arithmetic (DATEADD,DATEDIFF, intervals, week numbers, the first day of the week) is written differently everywhere and does not always count the same way. - Multiple result sets: a SQL Server or MySQL procedure that returns two or three result sets becomes a procedure with several cursors, or several functions, in PostgreSQL or Oracle. The application code that reads the results has to change as well.
- @@ROWCOUNT and @@ERROR: both are overwritten by almost every following statement, so they must be read immediately after the statement concerned. In the target that becomes
GET DIAGNOSTICS,ROW_COUNT()orSQL%ROWCOUNT, and oldIF @@ERROR <> 0checks become exception handling. - SET NOCOUNT: without
SET NOCOUNT ON, SQL Server sends a row-count message for each statement, and some older client code depends on it or trips over it. Other engines have no such setting; check how the application reads the number of affected rows. - Scope of temporary tables: a
#temptable created in a SQL Server procedure disappears when the procedure ends and is visible to the procedures it calls. In PostgreSQL and MySQL a temporary table lives until the end of the session, so a second call in the same session fails with “already exists” unless the code drops it or usesON COMMIT DROP. In Oracle the global temporary table is created once, outside the code. - Transactions and errors: in SQL Server many errors end only the statement and the transaction continues, unless
XACT_ABORTis on. In PostgreSQL any error aborts the whole transaction: every following statement fails until a rollback. Code that catches an error and carries on needs anEXCEPTIONblock, which works as a savepoint, or explicit savepoints. In Oracle a failed statement is undone, but the transaction stays open. - Functions with side effects: SQL Server functions cannot change data, so procedures are often converted into PostgreSQL functions, which can. The other direction is a trap: an Oracle function that writes data cannot be called from a query, and a PostgreSQL function wrongly declared
IMMUTABLEorSTABLEcan give wrong results. - Performance: cursors that process rows one at a time are slow on every engine, and a converted cursor loop is often slower than the original. Rewrite them as a single set-based statement where you can. Plans behave differently too: SQL Server compiles a procedure for the first parameter values it receives (parameter sniffing); PL/pgSQL prepares each statement and may switch to a generic plan after five executions, which
plan_cache_modecontrols. - Security context: a SQL Server procedure runs with the caller's rights, but ownership chaining lets it read tables the caller cannot, and
EXECUTE ASchanges the user. PostgreSQL functions run as the caller unless declaredSECURITY DEFINER(then also set a fixedsearch_path). MySQL routines run as theirDEFINERby default, Oracle procedures with the owner's rights unless declaredAUTHID CURRENT_USER. Map this deliberately, or permissions end up too broad or too narrow.
Estimating the effort
The number of objects says little on its own; their size and the features they use say much more. As a rough guide:
- Easy: short procedures and functions, up to a few dozen lines, with plain
SELECT,INSERT,UPDATEandDELETE, simple parameters and no dynamic SQL. Tools convert most of these correctly; review and testing remain. - Medium: up to a few hundred lines, with cursors, temporary tables,
TRY … CATCHwith transaction logic, several result sets,MERGE, date arithmetic or triggers. Expect manual work on every object. - Hard: dynamic SQL built from strings, references to other databases or linked servers, CLR assemblies,
xp_cmdshell,sp_OAprocedures, mail, file and web calls (sp_send_dbmail,UTL_FILE,UTL_HTTP), Oracle packages with state, autonomous transactions, and procedures of a thousand lines or more. These need a redesign, often partly in the application.
Count the hard objects separately: a handful of them often takes more time than all the easy ones together. Code that nobody calls any more does not need converting, so checking usage first can save a lot.
The free scan makes this inventory for you. It lists every procedure, function and trigger with its line count and the features that make a rewrite harder, such as cursors, dynamic SQL or TRY/CATCH. The script counts and detects these inside your database; the result contains no code text, and the analysis runs in your browser.
Testing: same input, same output
A converted procedure is finished when it gives the same results as the original, not when it compiles. The most dependable method is a direct comparison:
- Restore a copy of production on the old engine and load the same data into the new one.
- Collect realistic calls: parameters from application logs, Query Store or a trace, plus edge cases such as NULL, empty strings, zero rows, very long text, and dates around midnight and month ends.
- Run each call on both sides and compare everything: result sets (rows, column types, and order where the application depends on it), output parameters, the rows changed in the tables and the errors raised.
- Automate the comparison so that you can repeat it after every fix. Unit-test frameworks help: tSQLt for SQL Server, pgTAP for PostgreSQL, utPLSQL for Oracle and MyTAP for MySQL.
- Finally, test the application itself against the new database, including reports, batch jobs and interfaces that call the database directly.
Keep the old system available, read-only, until the new one has run in production for a while. It is the reference when someone reports that a figure “used to be different”.
Should you rewrite at all?
Rewriting is usually the most expensive part of changing engines. Before you start, consider the alternatives:
- Stay on the same engine, in the cloud. Azure SQL Managed Instance, Amazon RDS for SQL Server, Oracle or MySQL, and Oracle Database@Azure, @AWS and @Google Cloud run the existing code largely unchanged. Azure SQL Database is more restrictive (no cross-database queries, CLR or SQL Server Agent), so some code changes even there.
- Babelfish for Aurora PostgreSQL. Aurora PostgreSQL then understands T-SQL and the SQL Server network protocol, so many procedures run without a rewrite. Not every feature is supported; Babelfish Compass shows in advance which ones in your code are not.
- Move logic to the application. Real business logic, such as calculations, validation and workflows, is often easier to test and maintain in application code. That is a bigger change, but it removes the dependency on a database dialect for good. Set-based work on large volumes is usually better left in the database.
- Rewrite in stages. Convert what blocks the migration first and clean up the rest afterwards, instead of improving everything at once.
The right choice depends on why you are migrating. If the goal is to stop paying for licences, a rewrite to PostgreSQL can be worth it; if the goal is to leave an old server, staying on the same engine is usually faster and cheaper.
Questions
What is the difference between a stored procedure and a function?
A procedure is called on its own and can run several statements, manage transactions and return output parameters or result sets. A function returns a value or a table and is used inside a query. What each may do differs per engine: SQL Server functions cannot change data, PostgreSQL functions can, and in PostgreSQL only procedures can commit.
Can a tool convert my stored procedures automatically?
Partly. AWS DMS Schema Conversion, SSMA and ora2pg convert simple code well and mark what they cannot convert. Complex code, dynamic SQL and differences in behaviour need manual work, and every converted object needs testing.
Do I have to rewrite T-SQL to move to PostgreSQL?
On every PostgreSQL platform except Babelfish for Aurora PostgreSQL, yes: T-SQL has to become PL/pgSQL or application code. Babelfish runs a large part of T-SQL, but not all of it.
Why does PostgreSQL say “current transaction is aborted”?
Because an earlier statement in the same transaction failed. PostgreSQL then refuses every statement until a rollback. Code that catches errors and continues needs an EXCEPTION block or a savepoint around the statement that may fail.
How long does it take to rewrite a stored procedure?
From minutes for a short procedure that a tool converts correctly, to days for a long procedure with dynamic SQL and external calls. Testing often takes as long as converting. An inventory with line counts and features per object gives a better estimate than an average.
Are triggers converted the same way as procedures?
The method is the same, but check whether the trigger fires per statement or per row. SQL Server triggers are statement-level and see all changed rows in inserted and deleted; MySQL triggers are row-level; PostgreSQL and Oracle support both.
Does the scan read my code?
The script runs inside your database and counts lines and features per object. The result contains names, counts and feature flags, no code text and no table data, and it is analysed in your browser without being uploaded.
Read next
- Migrating SQL Server or Oracle to PostgreSQL
Migrating from SQL Server or Oracle to PostgreSQL: data types, identifiers, procedural code, tools such as pgloader and ora2pg, managed PostgreSQL in the cloud and a free scan. - SQL Server features that other databases and cloud services lack
SSIS, SSRS, Agent, Service Broker, CLR, Database Mail, linked servers, MSDTC, FILESTREAM: which cloud targets support them and what replaces them. - Database migration routes and downtime: offline, minimal or near-zero
Offline, minimal or near-zero downtime: how to choose a database migration route, what it costs, what breaks online, and the routes per engine.
See how much code you would have to rewrite: the free scan lists every procedure, function and trigger with its line count and the features that make a rewrite harder. Nothing is uploaded.
Start the free scan