π SQL Server Trick: Returning a Row as JSON Using a Stored Procedure
In modern applications, especially those involving APIs or frontend frameworks, JSON has become the de facto format for data exchange. Fortunately, SQL Server makes it easy to return query results in JSON format with FOR JSON PATH
. But what if you want a dynamic stored procedure that can return any row from any table as a JSON object?
Letβs walk through a stored procedure that does exactly that.
π¦ What It Does
This stored procedure, GetRowAsJson
, allows you to retrieve a single row from any table by its primary key and return it as a JSON object.
Parameters:
@table_name
β The name of the table to query.@pk_column
β The name of the primary key column (or a unique column).@pk_value
β The value of the primary key to filter on.
π§ The Stored Procedure
CREATE PROCEDURE GetRowAsJson
@table_name NVARCHAR(128),
@pk_column NVARCHAR(128),
@pk_value NVARCHAR(128)
AS
BEGIN
DECLARE @sql NVARCHAR(MAX);
SET @sql = N'SELECT * FROM ' + QUOTENAME(@table_name) +
N' WHERE ' + QUOTENAME(@pk_column) + N' = @val FOR JSON PATH, WITHOUT_ARRAY_WRAPPER';
EXEC sp_executesql @sql, N'@val NVARCHAR(128)', @val = @pk_value;
END;
βοΈ How It Works
- Dynamic SQL Construction:
It builds aSELECT
statement usingQUOTENAME
to prevent SQL injection and syntax errors. - Parameter Binding:
It usessp_executesql
with a parameterized query (@val
) to safely pass in the primary key value. - JSON Output:
By usingFOR JSON PATH, WITHOUT_ARRAY_WRAPPER
, the result is a single JSON object instead of an array.
π§ͺ Example Usage
Suppose you have a table named Users
with a primary key column UserId
. To get the row where UserId = 42
as JSON:
EXEC GetRowAsJson
@table_name = 'Users',
@pk_column = 'UserId',
@pk_value = '42';
Output:
{
"UserId": 42,
"Username": "jdoe",
"Email": "jdoe@example.com"
}
π Security Tip
While QUOTENAME
and sp_executesql
reduce SQL injection risks, avoid exposing this procedure directly to untrusted users. Consider wrapping it with application logic that enforces table/column restrictions.
β Use Cases
- Building REST APIs directly from SQL Server
- Generating JSON for frontend JavaScript apps
- Data export tools or dashboards
π Conclusion
With just a few lines of T-SQL, you can add flexible JSON output capabilities to your SQL Server database. GetRowAsJson
makes it easy to fetch data dynamically and serve it in a modern, API-friendly format.