The desired SQL statements
As usual, the easiest way to build a template is to start with a copy of the output you want. Here is the procedure for the Person.AddressType table in the AdventureWorks sample database:
CREATE OR ALTER PROCEDURE Person.GetAddressTypeJson
WITH EXECUTE AS CALLER
AS
BEGIN
SET NOCOUNT ON;
SET TRANSACTION ISOLATION LEVEL READ COMMITTED;
SELECT
[AddressTypeID],
[Name],
[rowguid],
[ModifiedDate]
FROM
[Person].[AddressType]
FOR JSON PATH, ROOT('AddressType');
END
GO
Running EXEC Person.GetAddressTypeJson returns the whole table as one JSON document, shaped like this (values shortened):
{"AddressType":[{"AddressTypeID":1,"Name":"Billing","rowguid":"…","ModifiedDate":"…"},{"AddressTypeID":2,…},…]}
The statement contains two kinds of variable information. Everything else in the template is static text.
| Kind of information | Where it appears |
|---|---|
| Values the user chooses from a short list | The EXECUTE AS value (CALLER), the isolation level (READ COMMITTED) and the FOR JSON mode (PATH). |
| Values CodeSmith Generator reads from the database once the user picks a table | The schema (Person) and table name (AddressType) in the procedure name, the source table and the JSON root; and the column list. |
About the SQL
You don't need to know every option in detail to follow this tutorial, but here's what each part does:
| Part | What it does |
|---|---|
CREATE OR ALTER PROCEDURE |
Creates the procedure, or replaces it if it already exists, so the script can be run again after the table changes. |
WITH EXECUTE AS |
The security context the procedure runs in: CALLER (the user who runs it), OWNER (the procedure's owner) or SELF (the user who created or last altered it). |
SET NOCOUNT ON |
Stops SQL Server sending a "rows affected" message, which some clients mistake for a result. |
SET TRANSACTION ISOLATION LEVEL |
How the query's reads interact with other transactions: READ UNCOMMITTED, READ COMMITTED, REPEATABLE READ, SNAPSHOT or SERIALIZABLE. SNAPSHOT needs ALLOW_SNAPSHOT_ISOLATION turned on for the database. |
FOR JSON PATH |
Returns the result as JSON, with the column names as property names. FOR JSON AUTO shapes the output from the tables in the query instead. |
ROOT('AddressType') |
Wraps the rows in a single object with this property name. |
Next: Create the template