### KQL Command Examples Source: https://jamsql.com/docs/kusto-kql Examples of administrative commands that can be executed alongside standard queries. ```kql .show tables ``` ```kql .show version ``` -------------------------------- ### Install Claude Code and Codex CLI Source: https://jamsql.com/docs/ai-integrations-mcp Run either or both commands to install the AI agents. Jam SQL Studio auto-detects whichever CLIs are on your machine. ```bash npm i -g @anthropic-ai/claude-code # Claude Code npm i -g @openai/codex # Codex CLI ``` -------------------------------- ### Jam SQL CLI commands for status, connections, queries, and MCP Source: https://jamsql.com/docs/ai-integrations-mcp A set of shell commands for the Jam SQL CLI. Use 'jam-sql doctor' to check installation and pairing, 'jam-sql status' for pairing and app status, 'jam-sql launch' to start the app, 'jam-sql connections' to list saved connections, 'jam-sql query' to execute a query, 'jam-sql tools' and 'jam-sql resources' to list MCP tools and resources, 'jam-sql call' to invoke an MCP tool, 'jam-sql read' to read an MCP resource, and 'jam-sql unpair' to remove stored credentials. ```shell # Check installation and pairing status jam-sql doctor # Show pairing + app status jam-sql status # Launch the app if not running jam-sql launch # List saved connections jam-sql connections # Execute a query jam-sql query -c production "SELECT * FROM users LIMIT 5" # List available MCP tools and resources jam-sql tools jam-sql resources # Call any MCP tool directly jam-sql call ui_open_tab '{"type": "query"}' # Read an MCP resource jam-sql read sql-studio://context/tabs # Remove stored credentials jam-sql unpair ``` -------------------------------- ### Run a simple query to list tables Source: https://jamsql.com/docs/getting-started Example SQL query to select the top 10 tables from the system catalog, ordered by name. Use this in the query editor after opening a new query tab. ```sql SELECT TOP 10 * FROM sys.tables ORDER BY name; ``` -------------------------------- ### Add jam-sql skill to AI agents Source: https://jamsql.com/docs/ai-integrations-mcp Run this command to auto-detect and install the jam-sql skill for supported agents like Claude Code, Cursor, Copilot, Codex, Windsurf, and more. The CLI is bundled with the app and installed to your PATH. ```bash jam-sql add-skill ``` -------------------------------- ### Product distribution (pie chart) query Source: https://jamsql.com/docs/charts Returns one label column and one value column for a pie chart. Uses COUNT(*) to get the count per product type. ```sql SELECT ProductType, COUNT(*) AS Count FROM Products GROUP BY ProductType; ``` -------------------------------- ### Compare T-SQL and PL/pgSQL for a simple order count routine Source: https://jamsql.com/docs/t-sql-vs-plpgsql Shows the same 'get a customer's order count' routine in T-SQL and PL/pgSQL to illustrate the four structural changes: named parameters instead of @params, a DECLARE section, SELECT ... INTO instead of SELECT @x = ..., and RETURN instead of a trailing result-set SELECT. ```sql -- T-SQL (SQL Server) CREATE PROCEDURE dbo.GetOrderCount @CustomerId INT AS BEGIN DECLARE @Total INT; SELECT @Total = COUNT(*) FROM dbo.Orders WHERE CustomerId = @CustomerId; SELECT @Total AS OrderCount; END; ``` ```sql -- PL/pgSQL (PostgreSQL) CREATE FUNCTION get_order_count(p_customer_id INT) RETURNS INT LANGUAGE plpgsql AS $$ DECLARE v_total INT; BEGIN SELECT COUNT(*) INTO v_total FROM orders WHERE customer_id = p_customer_id; RETURN v_total; END; $$; ``` -------------------------------- ### Create login role, group role, and grant schema privileges Source: https://jamsql.com/docs/security SQL statements generated by the role form for creating a login role with attributes, a group role, and granting schema privileges including default privileges for future tables. The example uses the 'app' schema and roles 'app_user' and 'app_readers'. ```sql -- Login role with attributes CREATE ROLE "app_user" WITH LOGIN PASSWORD '…' CREATEDB CONNECTION LIMIT 10 VALID UNTIL '2026-12-31'; -- Group role and membership CREATE ROLE "app_readers" WITH NOLOGIN; GRANT "app_readers" TO "app_user"; -- Schema privileges, including future tables GRANT SELECT ON ALL TABLES IN SCHEMA "app" TO "app_readers"; ALTER DEFAULT PRIVILEGES IN SCHEMA "app" GRANT SELECT ON TABLES TO "app_readers"; ``` -------------------------------- ### DROP statements for different database engines Source: https://jamsql.com/docs/scripting Shows engine-appropriate DROP syntax: SQL Server/PostgreSQL/MySQL/SQLite use IF EXISTS, while Oracle uses plain DROP because it lacks IF EXISTS. The example includes a comment for Oracle. ```sql -- SQL Server / PostgreSQL / MySQL / SQLite DROP TABLE IF EXISTS [dbo].[Customers]; -- Oracle (no IF EXISTS) DROP TABLE HR.CUSTOMERS; ``` -------------------------------- ### Grant debug privileges Source: https://jamsql.com/docs/plsql-debugger Run these statements as DBA to grant the privileges required for the PL/SQL Debugger. The debugger checks for these privileges when a session starts and reports missing ones with the exact GRANT statements. ```sql GRANT DEBUG CONNECT SESSION TO your_user; GRANT DEBUG ANY PROCEDURE TO your_user; GRANT EXECUTE ON SYS.DBMS_DEBUG TO your_user; ``` -------------------------------- ### Catch duplicate-key violation in PL/pgSQL Source: https://jamsql.com/docs/t-sql-vs-plpgsql PL/pgSQL example that catches a duplicate-key violation using the named condition unique_violation and raises a notice. The exception block automatically rolls back to an implicit savepoint, so statements in the block are undone when the handler is entered. ```PL/pgSQL -- PL/pgSQL: catch a duplicate-key violation by name, not by number BEGIN INSERT INTO accounts(email) VALUES (p_email); EXCEPTION WHEN unique_violation THEN RAISE NOTICE 'Account % already exists', p_email; END; ``` -------------------------------- ### Audited INSERT snippet with tab stops Source: https://jamsql.com/docs/snippets Use this snippet for audited INSERT statements in SQL Server. It inserts audit columns CreatedBy and CreatedAt using CURRENT_USER and GETDATE(). The tab stops ${1:table_name}, ${2:columns}, and ${3:values} guide the user through filling in the table, columns, and values, with $0 as the final cursor position. ```sql -- Prefix: insa -- Label: INSERT with audit columns INSERT INTO ${1:table_name} ( ${2:columns}, CreatedBy, CreatedAt ) VALUES ( ${3:values}, CURRENT_USER, GETDATE() )$0 ``` -------------------------------- ### Claude Desktop MCP Configuration (claude_desktop_config.json) Source: https://jamsql.com/docs/ai-integrations-mcp Configure Claude Desktop to use the jam-sql MCP server via mcp-remote proxy. Requires Node 20+ and the correct npx path. Replace /path/to/node20+/bin/npx with your actual Node 20+ npx path. ```json { "mcpServers": { "jam-sql": { "command": "/path/to/node20+/bin/npx", "args": [ "-y", "mcp-remote", "http://127.0.0.1:14507/mcp", "--header", "Authorization:${JAM_SQL_TOKEN}" ], "env": { "JAM_SQL_TOKEN": "Bearer YOUR_TOKEN_HERE" } } } } ``` -------------------------------- ### Pair the CLI with the running app Source: https://jamsql.com/docs/ai-integrations-mcp Run jam-sql pair to securely connect the CLI to a running Jam SQL Studio instance. A verification code is displayed in the terminal and must be confirmed against the dialog in the app before approving. ```bash # Pair with the running app (one-time setup) jam-sql pair # A verification code is displayed — confirm it matches # the dialog shown in Jam SQL Studio, then approve. ``` -------------------------------- ### Add a connection via jam-sql CLI Source: https://jamsql.com/docs/ai-integrations-mcp Use this command to add a new database connection from the CLI. It reads the password from stdin, test-connects first, and persists with the password encrypted at rest. If the test fails, nothing is saved. ```bash echo "$DB_PASSWORD" | jam-sql connection add \ --engine mssql --alias prod-analytics \ --server db.example.com --port 1433 \ --login app_reader --password-stdin \ --database AnalyticsDb ``` -------------------------------- ### Sample exported Azure Data Studio connections JSON Source: https://jamsql.com/docs/export-azure-data-studio-connections Shows the structure of an exported connections JSON file with a SQL Server connection and a connection group. The connection includes options like server, database, user, authenticationType, and providerName. ```json { "datasource.connections": [ { "options": { "connectionName": "Production AdventureWorks", "server": "prod-sql-01.example.com,1433", "database": "AdventureWorks2019", "user": "reporting_user", "authenticationType": "SqlLogin", "applicationName": "azdata", "trustServerCertificate": true, "encrypt": "Mandatory" }, "groupId": "C777F06B-202E-4480-B475-FA416154D458", "providerName": "MSSQL", "savePassword": true, "id": "8f9d1e4a-1c2b-4a0e-9c2a-1f2e3d4c5b6a" } ], "datasource.connectionGroups": [ { "name": "Production", "id": "C777F06B-202E-4480-B475-FA416154D458", "parentId": "ROOT", "color": "#515151" } ] } ``` -------------------------------- ### Revenue by region over time (grouped/stacked bar) query Source: https://jamsql.com/docs/charts Returns Month, Region, and Revenue columns for a grouped or stacked bar chart. In the builder, set X = Month, Value = Revenue (Sum), and Group By = Region. ```sql SELECT Month, Region, Revenue FROM MonthlySales; -- In the builder: X = Month, Value = Revenue (Sum), Group By = Region ``` -------------------------------- ### Create user, role, and grants for SQL Server Source: https://jamsql.com/docs/security DDL for creating a database user mapped to a login, creating a database role, adding the user to the role, and granting/denying schema permissions. SQL Server is the only supported engine with DENY. ```sql -- User mapped to a login CREATE USER [app_user] FOR LOGIN [app_user] WITH DEFAULT_SCHEMA = [dbo]; -- Database role and membership CREATE ROLE [app_readers]; ALTER ROLE [app_readers] ADD MEMBER [app_user]; -- Grant on a schema (SQL Server supports DENY as well as GRANT/REVOKE) GRANT SELECT ON SCHEMA::[app] TO [app_readers]; DENY DELETE ON SCHEMA::[app] TO [app_readers]; ``` -------------------------------- ### Export results via CLI (ui_export_results) Source: https://jamsql.com/docs/ai-integrations-mcp Use the jam-sql CLI to export query results to a file. The agent does not choose the destination; the app opens a save dialog. Formats include csv, json, xlsx, markdown, and sql. The scope can be set to all-rows for CSV exports. ```bash jam-sql call ui_export_results tabId=tab-1 format=xlsx jam-sql call ui_export_results tabId=tab-1 format=csv scope=all-rows ``` -------------------------------- ### JamSQL blueprint folder layout Source: https://jamsql.com/docs/database-blueprint Shows the folder layout of a JamSQL blueprint. The manifest jamsql-blueprint.json links databases and included object types; jamsql-meta-Dev.json holds per-link MetaInfo. Data artefacts are tracked and shared, while .jamsql/snapshots are per-user and gitignored. ```text my-blueprint/ ├── jamsql-blueprint.json ← manifest (linked DBs, included object types, schemas) ├── jamsql-meta-Dev.json ← per-link MetaInfo (loose FKs, JSON, enums) ├── README.md ├── .gitignore ├── Schemas/ │ └── dbo.sql ├── Tables/ │ ├── dbo.Users.sql │ └── dbo.Orders.sql ├── Views/ │ └── dbo.OrderSummary.sql ├── Sequences/ ← PostgreSQL / Oracle / SQL Server │ └── dbo.OrderNumber.sql ├── Programmability/ │ ├── Stored Procedures/ │ │ └── dbo.usp_UpdateOrder.sql │ ├── Functions/ │ │ └── dbo.fn_OrderTotal.sql │ └── User-Defined Types/ ← SQL Server table / alias / CLR types │ └── dbo.IntegerKeyValueList.sql ├── Data/ ← table data artefacts (tracked — shared with teammates) │ ├── dbo.Users.data.sql ← upsert / replay SQL for the table data │ └── dbo.Users.data.json ← row sidecar (PK, column types, captured rows) └── .jamsql/ └── snapshots/ ← per-user baseline cache (not shared, gitignored) ``` -------------------------------- ### Generate Script for Adding Column and Index Source: https://jamsql.com/docs/schema-compare Generated script for adding a column and index to the orders table, used in the promote dev → staging → production workflow. Save as 2026-05-06-orders-shipped-at.sql and apply with Open & Execute after backup. ```sql ALTER TABLE [dbo].[orders] ADD [shipped_at] DATETIME2 NULL; GO CREATE INDEX [IX_orders_shipped_at] ON [dbo].[orders] ([shipped_at]); GO ``` -------------------------------- ### Configure MCP server in Codex CLI config.toml Source: https://jamsql.com/docs/ai-integrations-mcp Add this configuration to ~/.codex/config.toml to register the Jam SQL MCP server with Codex CLI. The bearer token is read from the environment variable JAM_SQL_MCP_TOKEN, which you must export in your shell profile. ```toml [mcp_servers.jam-sql] url = "http://127.0.0.1:14507/mcp" bearer_token_env_var = "JAM_SQL_MCP_TOKEN" ``` -------------------------------- ### Declare metadata via CLI (metainfo_declare) Source: https://jamsql.com/docs/ai-integrations-mcp Use the jam-sql CLI to declare metadata for enum or JSON columns. The agent may suggest this when it finds itself redoing metadata work. The saved entry is badged AI-created or AI-updated. ```bash jam-sql call metainfo_declare kind=enum connectionId=abc123 database=mydb \ schema=dbo table=Orders column=status jam-sql call metainfo_declare kind=json connectionId=abc123 database=mydb \ schema=dbo table=Orders column=metadata ``` -------------------------------- ### Check Node.js Version Source: https://jamsql.com/docs/ai-integrations-mcp Verify Node.js version is v20.0.0 or higher, required for mcp-remote proxy used by Claude Desktop. ```bash node --version # Must be v20.0.0 or higher ``` -------------------------------- ### Register MCP server with Claude Code Source: https://jamsql.com/docs/ai-integrations-mcp Use this command to add the Jam SQL MCP server to Claude Code with a bearer token. The endpoint is http://127.0.0.1:14507/mcp and the token is YOUR_TOKEN_HERE. The --scope user flag registers it for the current user. ```bash claude mcp add --transport http jam-sql http://127.0.0.1:14507/mcp \ --header "Authorization: Bearer YOUR_TOKEN_HERE" \ --scope user ``` -------------------------------- ### Codex CLI Add MCP Server Source: https://jamsql.com/docs/ai-integrations-mcp Use the Codex CLI to add the jam-sql MCP server with the specified URL. ```bash codex mcp add jam-sql --url http://127.0.0.1:14507/mcp ``` -------------------------------- ### Sales by category (bar chart) query Source: https://jamsql.com/docs/charts Returns one category column and one value column for a bar chart. In the builder, set X = Category and Value = Amount with aggregation Sum, which allows skipping GROUP BY. ```sql SELECT Category, Amount FROM Orders; -- In the builder: X = Category, Value = Amount (Sum) ``` -------------------------------- ### Engine SQL equivalents for property = on path $.address.city Source: https://jamsql.com/docs/json-columns Shows the SQL emitted by Jam SQL Studio for the `property =` operator on path `$.address.city` across different database engines. The path syntax accepts JSONPath or shorthand, and the engine normalizes it. ```PostgreSQL data #>> '{address,city}' = 'Boston' ``` ```MySQL JSON_UNQUOTE(JSON_EXTRACT(data, '$.address.city')) = 'Boston' ``` ```SQL Server JSON_VALUE(data, '$.address.city') = 'Boston' ``` ```Oracle JSON_VALUE(data, '$.address.city') = 'Boston' ``` ```SQLite json_extract(data, '$.address.city') = 'Boston' ``` ```Azure Data Explorer (Kusto) | where tostring(data.address.city) == "Boston" ``` -------------------------------- ### Monthly revenue (line chart) query Source: https://jamsql.com/docs/charts Returns a date/period column on X and a numeric measure on Y for a line chart. Uses FORMAT to group by month and orders the result. ```sql SELECT FORMAT(OrderDate, 'yyyy-MM') AS Month, SUM(Amount) AS Revenue FROM Orders GROUP BY FORMAT(OrderDate, 'yyyy-MM') ORDER BY Month; ``` -------------------------------- ### Claude Code Project Scope Configuration (.mcp.json) Source: https://jamsql.com/docs/ai-integrations-mcp Configure the jam-sql MCP server for a specific project by creating .mcp.json in the project root. Supports environment variable expansion with ${VAR} syntax. ```json { "mcpServers": { "jam-sql": { "type": "http", "url": "${JAM_SQL_MCP_ENDPOINT:-http://127.0.0.1:14507/mcp}", "headers": { "Authorization": "Bearer ${JAM_SQL_MCP_TOKEN}" } } } } ``` -------------------------------- ### Execute stored procedure template for SQL Server Source: https://jamsql.com/docs/scripting SQL Server template for executing a stored procedure with parameters. It includes comments listing parameter types and directions, and uses OUTPUT markers for output parameters. The template is not auto-run; you fill in values and execute manually. ```sql -- Execute stored procedure [dbo].[GetCustomerOrders] -- Parameters: -- @CustomerID int -- @StartDate datetime -- @EndDate datetime -- @OrderStatus varchar (OUT) EXEC [dbo].[GetCustomerOrders] @CustomerID = , @StartDate = , @EndDate = , @OrderStatus = OUTPUT ``` -------------------------------- ### Script as CREATE for user-defined table type Source: https://jamsql.com/docs/scripting Script as CREATE output for a user-defined table type. Constraint names are intentionally omitted because SQL Server auto-generates them per instance, which would otherwise cause the script to fail when re-creating the type under a different name or differ between servers. ```sql CREATE TYPE [dbo].[IntegerKeyValueList] AS TABLE ( [Key] INT NULL, [Value] INT NULL ); ``` -------------------------------- ### Direct HTTP POST to MCP Endpoint Source: https://jamsql.com/docs/ai-integrations-mcp Make a JSON-RPC 2.0 request to list available tools on the MCP endpoint. Requires a valid bearer token. ```bash curl -X POST http://127.0.0.1:14507/mcp \ -H "Authorization: Bearer YOUR_TOKEN_HERE" \ -H "Content-Type: application/json" \ -d '{"jsonrpc":"2.0","method":"tools/list","id":1}' ``` -------------------------------- ### Loop in T-SQL and PL/pgSQL Source: https://jamsql.com/docs/t-sql-vs-plpgsql Looping with WHILE in T-SQL and PL/pgSQL. ```T-SQL WHILE @i < 10 BEGIN ... END ``` ```PL/pgSQL WHILE i < 10 LOOP ... END LOOP; ``` -------------------------------- ### Script as CREATE for alias type Source: https://jamsql.com/docs/scripting Script as CREATE output for a user-defined data type (alias type). Lengths are declared in characters, not the bytes stored in the catalog. ```sql CREATE TYPE [dbo].[Clave] FROM NVARCHAR(50) NOT NULL; ``` -------------------------------- ### Claude Code Verify MCP Connection Source: https://jamsql.com/docs/ai-integrations-mcp Run 'claude mcp list' to verify the MCP server is connected. Alternatively, type /mcp inside Claude Code to see connected servers. ```bash claude mcp list ``` -------------------------------- ### If/else in T-SQL and PL/pgSQL Source: https://jamsql.com/docs/t-sql-vs-plpgsql Conditional execution with IF/ELSE in T-SQL and PL/pgSQL. ```T-SQL IF @n > 0 BEGIN ... END ELSE BEGIN ... END ``` ```PL/pgSQL IF n > 0 THEN ... ELSE ... END IF; ``` -------------------------------- ### SQL Server script header for non-atomic sync Source: https://jamsql.com/docs/schema-compare Header comment generated in sync scripts when the 'Wrap in a single transaction' option is unticked or not available. States that each GO batch commits independently and that a failure leaves earlier statements applied, advising regeneration with the wrap option for atomicity. ```sql -- Atomicity: NONE — each GO batch commits on its own. If a statement fails, -- everything before it stays applied. Re-generate with -- "Wrap in a single transaction" for all-or-nothing. ``` -------------------------------- ### Set MCP Environment Variables Source: https://jamsql.com/docs/ai-integrations-mcp Export the MCP endpoint and token as environment variables for custom integrations that support environment-based configuration. ```bash export JAM_SQL_MCP_ENDPOINT="http://127.0.0.1:14507/mcp" export JAM_SQL_MCP_TOKEN="YOUR_TOKEN_HERE" ``` -------------------------------- ### Print/debug in T-SQL and PL/pgSQL Source: https://jamsql.com/docs/t-sql-vs-plpgsql Prints a debug message in T-SQL and PL/pgSQL. ```T-SQL PRINT 'msg'; ``` ```PL/pgSQL RAISE NOTICE 'msg'; ``` -------------------------------- ### Claude Code User Scope Configuration (~/.claude.json) Source: https://jamsql.com/docs/ai-integrations-mcp Configure the jam-sql MCP server for all projects by editing ~/.claude.json. Uses HTTP transport with a static bearer token. ```json { "mcpServers": { "jam-sql": { "type": "http", "url": "http://127.0.0.1:14507/mcp", "headers": { "Authorization": "Bearer YOUR_TOKEN_HERE" } } } } ``` -------------------------------- ### Check debug compilation with ALL_PLSQL_OBJECT_SETTINGS Source: https://jamsql.com/docs/plsql-debugger Verify that a program unit is compiled with debug information. Replace YOUR_SCHEMA and YOUR_OBJECT with the actual schema and object names. If the plsql_debug column does not indicate debug compilation, breakpoints will not be hit. ```sql SELECT name, plsql_debug FROM ALL_PLSQL_OBJECT_SETTINGS WHERE owner = 'YOUR_SCHEMA' AND name = 'YOUR_OBJECT'; ``` -------------------------------- ### Set JAM_SQL_MCP_TOKEN Environment Variable Source: https://jamsql.com/docs/ai-integrations-mcp Export the JAM_SQL_MCP_TOKEN environment variable in your shell profile (~/.zshrc or ~/.bashrc) for Codex CLI to use. ```bash export JAM_SQL_MCP_TOKEN="YOUR_TOKEN_HERE" ``` -------------------------------- ### Windows authentication login DDL Source: https://jamsql.com/docs/security Generated statement for creating a Windows authentication login from a domain account. ```sql CREATE LOGIN [DOMAIN\username] FROM WINDOWS WITH DEFAULT_DATABASE = [mydb]; ``` -------------------------------- ### SQL authentication login DDL Source: https://jamsql.com/docs/security Generated statement for creating a SQL authentication login with password, default database, and password policy check. ```sql CREATE LOGIN [app_user] WITH PASSWORD = N'…', DEFAULT_DATABASE = [mydb], CHECK_POLICY = ON; ``` -------------------------------- ### Enum Column Filtering Source: https://jamsql.com/docs/kusto-kql The filter chip emits a where clause using the in operator for low-cardinality columns. ```kql | where Column in ("A", "B") ``` -------------------------------- ### JSON Column Path Filtering Source: https://jamsql.com/docs/kusto-kql Filtering on dynamic JSON columns emits a KQL dynamic accessor. ```kql | where customDimensions.tenant == "acme" ``` -------------------------------- ### Loop over rows in T-SQL and PL/pgSQL Source: https://jamsql.com/docs/t-sql-vs-plpgsql Looping over rows: T-SQL uses a cursor with DECLARE ... CURSOR FOR ... and FETCH, while PL/pgSQL uses FOR r IN SELECT ... LOOP ... END LOOP. The PL/pgSQL form is shorter and faster because it avoids materializing a server cursor. ```T-SQL DECLARE ... CURSOR FOR ... ``` ```PL/pgSQL FOR r IN SELECT ... LOOP ... END LOOP; ``` -------------------------------- ### Return a result set in T-SQL and PL/pgSQL Source: https://jamsql.com/docs/t-sql-vs-plpgsql Returns a result set: T-SQL uses an implicit SELECT, while PL/pgSQL uses RETURN QUERY SELECT ... in a function that returns TABLE. ```T-SQL SELECT ... ; ``` ```PL/pgSQL RETURN QUERY SELECT ...; ``` -------------------------------- ### Raise an error in T-SQL and PL/pgSQL Source: https://jamsql.com/docs/t-sql-vs-plpgsql Raises an error in T-SQL and PL/pgSQL. ```T-SQL THROW 50000, 'msg', 1; ``` ```PL/pgSQL RAISE EXCEPTION 'msg'; ``` -------------------------------- ### Re-raise current error in T-SQL and PL/pgSQL Source: https://jamsql.com/docs/t-sql-vs-plpgsql Re-raises the current error in T-SQL and PL/pgSQL. ```T-SQL THROW; ``` ```PL/pgSQL RAISE; ``` -------------------------------- ### Guarded block in T-SQL and PL/pgSQL Source: https://jamsql.com/docs/t-sql-vs-plpgsql Guarded block for error handling: T-SQL uses TRY/CATCH, PL/pgSQL uses BEGIN ... EXCEPTION. ```T-SQL BEGIN TRY ... END TRY BEGIN CATCH ... END CATCH ``` ```PL/pgSQL BEGIN ... EXCEPTION WHEN ... THEN ... END; ``` -------------------------------- ### Assign from a query in T-SQL and PL/pgSQL Source: https://jamsql.com/docs/t-sql-vs-plpgsql Assigns a query result to a variable in T-SQL and PL/pgSQL. ```T-SQL SELECT @n = COUNT(*) FROM t; ``` ```PL/pgSQL SELECT COUNT(*) INTO n FROM t; ``` -------------------------------- ### Assign a value to a variable in T-SQL and PL/pgSQL Source: https://jamsql.com/docs/t-sql-vs-plpgsql Assigns a literal value to a variable in T-SQL and PL/pgSQL. ```T-SQL SET @n = 5; ``` ```PL/pgSQL n := 5; ``` -------------------------------- ### SQL query for Rails-style polymorphic association with loose FK Source: https://jamsql.com/docs/loose-foreign-keys Use this query to join comments to posts via a loose foreign key with a source filter on commentable_type. The filter ensures only comments with commentable_type = 'Post' are joined to posts. This models a polymorphic association where commentable_id can reference different tables. ```sql -- Rails-style polymorphic association -- Loose FK: commentable_id → posts.id (source filter: commentable_type = 'Post') SELECT c.id, c.body, p.title AS post_title FROM comments c JOIN posts p ON p.id = c.commentable_id WHERE c.commentable_type = 'Post'; ``` -------------------------------- ### Error message in T-SQL and PL/pgSQL Source: https://jamsql.com/docs/t-sql-vs-plpgsql Retrieves the error message in T-SQL and PL/pgSQL. ```T-SQL ERROR_MESSAGE() ``` ```PL/pgSQL SQLERRM ``` -------------------------------- ### Microsoft Entra ID login DDL Source: https://jamsql.com/docs/security Generated statement for creating a login from an external provider (Microsoft Entra ID). ```sql CREATE LOGIN [user@contoso.com] FROM EXTERNAL PROVIDER WITH DEFAULT_DATABASE = [mydb]; ``` -------------------------------- ### Error code in T-SQL and PL/pgSQL Source: https://jamsql.com/docs/t-sql-vs-plpgsql Retrieves the error code in T-SQL and PL/pgSQL. ```T-SQL ERROR_NUMBER() ``` ```PL/pgSQL SQLSTATE ``` -------------------------------- ### Declare a variable in T-SQL and PL/pgSQL Source: https://jamsql.com/docs/t-sql-vs-plpgsql Declares a variable in T-SQL with DECLARE @n INT; and in PL/pgSQL with n INT; inside the DECLARE block. ```T-SQL DECLARE @n INT; ``` ```PL/pgSQL n INT; ``` -------------------------------- ### Return a scalar in T-SQL and PL/pgSQL Source: https://jamsql.com/docs/t-sql-vs-plpgsql Returns a scalar value from a function or procedure in T-SQL and PL/pgSQL. ```T-SQL RETURN @n; ``` ```PL/pgSQL RETURN n; ``` -------------------------------- ### Catch a specific error in T-SQL and PL/pgSQL Source: https://jamsql.com/docs/t-sql-vs-plpgsql Catches a specific error: T-SQL inspects ERROR_NUMBER(), PL/pgSQL uses a named condition like WHEN unique_violation THEN ... ```T-SQL Inspect ERROR_NUMBER() ``` ```PL/pgSQL WHEN unique_violation THEN ... ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.