Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@yorek
Last active October 1, 2019 06:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yorek/59074a4c4176191687d6a17dabb426ed to your computer and use it in GitHub Desktop.
Save yorek/59074a4c4176191687d6a17dabb426ed to your computer and use it in GitHub Desktop.
Access to JSON file content using T-SQL
/*
Create the Database Master Key, if needed
*/
CREATE MASTER KEY ENCRYPTION BY PASSWORD = 'My-L0ng&Str0ng_P4ss0wrd!';
GO
/*
Create database scoped credentials to store the Shared Access Signature (SAS)
needed to access the Azure Blob Container. More info on Azure Blob SAS here:
https://docs.microsoft.com/en-us/azure/storage/storage-dotnet-shared-access-signature-part-1
SAS can be created right from Azure Portal or Azure CLI
*/
CREATE DATABASE SCOPED CREDENTIAL [Azure-Storage-Credentials]
WITH IDENTITY = 'SHARED ACCESS SIGNATURE',
SECRET = '<your SAS signature, WITHOUT any leading "?">';
GO
/*
Now create the external data source and point it to the Azure Blob Store
*/
CREATE EXTERNAL DATA SOURCE [Azure-Storage]
WITH
(
TYPE = BLOB_STORAGE,
LOCATION = 'https://<storage-account>.blob.core.windows.net',
CREDENTIAL= [Azure-Storage-Credentials]
);
GO
/*
Access the file content via SINGLE_BLOB BULK OPENROWSET
and pass it to OPENJSON
*/
WITH cte AS
(
SELECT
CAST(BulkColumn AS NVARCHAR(MAX)) AS JsonData
FROM
OPENROWSET(BULK '<container>/<blob>', DATA_SOURCE = 'Azure-Storage', SINGLE_CLOB) AS AzureBlob
)
SELECT
j.*
FROM
cte
CROSS APPLY
OPENJSON(cte.JsonData) j
go
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment