- Getting Started with Azure Cosmos DB
- CRUD Operations In Azure Cosmos DB Using ASP.NET Core Web API
- ASP.NET Core Blazor Server CRUD Operations with Azure Cosmos DB and C#
- How to use Azure Cosmos DB Locally for Development
In this article, we will learn how to create stored procedures in Azure Cosmos DB. Let’s begin with the basics so everyone can understand, including beginners.
What is a Cosmos DB Stored Procedure?
Azure Cosmos DB can understand and work with many conditions and queries. For instance, if you are using the SQL API, you can use SQL queries to ask questions about your data. So, you could ask, "Can you show me all the employees who live in Latur?.
However, there’s a difference when it comes to stored procedures. Unlike SQL databases, where you might write stored procedures using SQL, in Azure Cosmos DB, you write stored procedures in JavaScript.
Why use stored procedures?
- Efficiency
- Atomicity
- Speed
- Security
- Maintainability
- Consistency
Efficiency
Atomicity
Speed
Security
They help keep the data safe by limiting direct access to the data in the database, reducing the risk of unwanted access.
Maintainability
Consistency
Now lets start implementing the stored procedures for the Azure Cosmos DB SQL API step by step.
Step 1 : Set up Prerequisites
- CRUD Operations In Azure Cosmos DB Using ASP.NET Core Web API
- ASP.NET Core Blazor Server CRUD Operations with Azure Cosmos DB and C#
{ "id": "1", "Name": "Sarika S", "Country": "India", "City": "Phaltan", "Department": "IT", "Designation": "Senior DataBase Architect" }
Step 2 : Open the Cosmos DB Emulator or Explorer
- Navigate to the SQL API section under Explorer.
- Expand the Employee section.
- Access the Stored Procedures section.
- Click on New Stored Procedure to create a new procedure.
Step 3 : Create the Stored Procedure to Get All Employees
- Remove the existing default code.
- Use the code as given in the editor.
- Provide the unique ID for the stored procedure for unique identification.
- Click on Save, and then the stored procedure will be shown under the stored procedure blend.
function getAllEmployees() { var context = getContext(); var response = context.getResponse(); var collection = context.getCollection(); var isAccepted = collection.queryDocuments( collection.getSelfLink(), 'SELECT * FROM Employees', function (err, feed, options) { if (err) { throw new Error("Error while querying for documents: " + err.message); } response.setBody(feed); } ); if (!isAccepted) { throw new Error('The query was not accepted by the server.'); } }
Please download the stored procedure code from Github for more details.
Summary
Post a Comment