SQL Query Tools
Connect your AI agents directly to SQL Server databases, enabling them to retrieve, update, and manage data through secure, parameterized queries.
Overview
SQL Query Tools allow your agents to execute custom SQL queries against Azure SQL Server databases. Instead of complex API integrations, administrators can create database query tools through a guided wizard that the AI can use to answer questions, look up records, and update data in real-time.
Use Cases
- Customer Lookup - Retrieve customer details by ID, email, or name from your CRM database
- Order Status - Check order status, shipping information, and delivery tracking
- Inventory Queries - Look up product availability, stock levels, and warehouse locations
- Data Updates - Update customer contact information or order status (with confirmation)
- Financial Reporting - Query sales figures, outstanding balances, and payment history
- System Monitoring - Check active users, error logs, or system statistics
How It Works
Connection SQL Query Agent Tool
Configuration Definition Execution
| | |
v v v
+-----------+ +-----------+ +-----------+
| Database | --> | Query + | --> | Paramete- |
| Server + | | Parameters| | rized |
| Credentials| | + Tool | | Execution |
+-----------+ | Description| +-----------+
+-----------+ |
| v
v +-----------+
+-----------+ | Formatted |
| Auto- | | Results |
| generated | | for AI |
| Tool | +-----------+
+-----------+
Prerequisites
Before creating SQL Query Tools:
- Database Access - Have your SQL Server connection details ready (server, database, credentials)
- Network Connectivity - Ensure your database is accessible from Azure (firewall rules configured)
- Query Knowledge - Know the tables and columns you want to query
- Permissions - Have appropriate database permissions for the queries you want to run
Managing Connections
Navigate to SQL Tools
- Navigate to Build > Connections > SQL Tools
- The page displays two tabs: Connections and Queries
- Click the Connections tab to manage database connections
Creating a Connection
- Click Add Connection
- Fill in the connection details:
| Field | Description |
|---|---|
| Connection Name | Unique identifier (lowercase, hyphens, numbers only) |
| Display Name | Friendly name shown in the UI |
| Description | Optional description of this database |
| Server Name | SQL Server hostname (e.g., mydb.database.windows.net) |
| Database Name | Target database name |
| Authentication Type | SQL Authentication, Azure AD, or Managed Identity |
| Username | Database username (for SQL auth) |
| Password | Database password (encrypted at rest) |
| Connection Timeout | Max seconds to establish connection (default: 30) |
| Command Timeout | Max seconds for query execution (default: 60) |
| Allow Write Operations | Enable INSERT, UPDATE, DELETE queries |
| Max Rows (Default) | Default row limit for results (default: 100) |
| Max Rows (Absolute) | Hard maximum row limit (default: 1000) |
- Click Test Connection to verify connectivity
- Click Save to create the connection
Authentication Types
| Type | When to Use |
|---|---|
| SQL Authentication | Standard username/password authentication |
| Azure Active Directory | Use Azure AD credentials |
| Managed Identity | Azure Functions managed identity (no credentials stored) |
Write Operation Protection
The Allow Write Operations setting controls what types of queries can be created:
- Disabled (default): Only SELECT queries are allowed. This is the safest option for read-only integrations.
- Enabled: INSERT, UPDATE, DELETE, and stored procedure execution are permitted.
Enable write operations only when necessary. All write operations are logged for auditing, and you can optionally require confirmation for sensitive updates.
Editing and Deleting Connections
- Edit: Click the edit button on a connection card to modify settings
- Delete: Click the delete button. This also deletes all queries using that connection.
Deleting a connection also removes all SQL queries that use it and their tool assignments to agents.
Creating SQL Query Tools
Navigate to Queries
- Navigate to Build > Connections > SQL Tools
- Click the Queries tab
- Click Add Query to start the wizard
Step 1: Basic Information
Fill in the query identification details:
| Field | Description |
|---|---|
| Connection | Select the database connection to use |
| Query Name | Unique identifier for this query |
| Display Name | Friendly name shown in the UI |
| Description | What this query does |
| Tool Name | Function name the AI will call (lowercase, underscores) |
| Tool Description | Detailed description for the AI to understand when to use this tool |
Write the tool description as if explaining to a person when they should use this query. Include what information it returns and when it's appropriate to call.
Good example: "Look up customer information by their email address. Returns customer name, company, account status, and contact details. Use when you need to identify who sent an email or verify customer information."
Step 2: SQL Query Editor
Enter your SQL query:
SELECT
CustomerId,
CustomerName,
Email,
Phone,
Status,
CreatedAt
FROM Customers
WHERE Email = @email
Configure query options:
| Option | Description |
|---|---|
| Query Type | SELECT, INSERT, UPDATE, DELETE, or EXEC (auto-detected) |
| Is Stored Procedure | Check if calling a stored procedure |
| Max Rows | Override connection default (optional) |
| Return Format | table (markdown), json, or summary |
Return Formats:
| Format | Best For |
|---|---|
| table | Human-readable markdown tables, good for small result sets |
| json | Structured data, good for AI processing |
| summary | Large result sets, returns count and sample row |
Click Parse Parameters to extract @parameter placeholders from your query.
Step 3: Parameter Configuration
For each parameter detected in your query, configure:
| Setting | Description |
|---|---|
| Parameter Name | The @param name from your query (read-only) |
| Type | SQL data type (INT, NVARCHAR, DATETIME, etc.) |
| Length | Character length for VARCHAR/NVARCHAR types |
| Required | Whether this parameter must be provided |
| Default Value | Value to use if not provided (optional) |
| Description | Explanation for the AI about what value to provide |
| Validation Rules | JSON constraints (min, max, pattern, enum) |
Example Parameter Configuration:
| Parameter | Type | Required | Description |
|---|---|---|---|
@email | NVARCHAR(255) | Yes | Customer's email address |
@status | NVARCHAR(50) | No (default: Active) | Filter by customer status |
Validation Rules:
// For integers with range
{"minimum": 1, "maximum": 9999}
// For strings with pattern
{"pattern": "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$"}
// For strings with allowed values
{"enum": ["Active", "Inactive", "Pending"]}
Step 4: Test Execution
Before saving, test your query:
- Enter test values for each parameter
- Click Execute Test
- Review the results
Successful test shows:
- Row count and execution time
- Sample results in your chosen format
- Column names and data types
Failed test shows:
- Error message from the database
- SQL state code for troubleshooting
Use realistic test values that you know exist in your database. This validates both the query syntax and your parameter types.
Step 5: Grant Tool Access
After saving, choose which agents can use this tool:
- Select agents from the list of available agents and SMEs
- Check the boxes next to agents that should have access
- Click Grant Access
You can also assign tools later from the agent configuration page.
Sample Query Configurations
Customer Lookup by Email
SELECT CustomerId, CustomerName, Email, Phone, Status
FROM Customers
WHERE Email = @email
Parameters:
@email(NVARCHAR 255, required): Customer email to search
Tool Description: "Look up customer information by email address. Returns customer ID, name, contact details, and account status."
Order Status Check
SELECT
o.OrderId,
o.OrderNumber,
o.OrderDate,
o.Status,
o.TotalAmount,
o.TrackingNumber,
c.CustomerName
FROM Orders o
INNER JOIN Customers c ON o.CustomerId = c.CustomerId
WHERE o.OrderNumber = @orderNumber
Parameters:
@orderNumber(NVARCHAR 50, required): Order number to look up
Tool Description: "Check the status of an order by order number. Returns order details including status, total amount, and shipping tracking number."
Update Customer Email
UPDATE Customers
SET Email = @newEmail, UpdatedAt = GETUTCDATE()
WHERE CustomerId = @customerId
Parameters:
@customerId(INT, required): Customer ID to update@newEmail(NVARCHAR 255, required): New email address
Tool Description: "Update a customer's email address. Requires customer ID and new email. Use only when the customer explicitly requests an email change."
Ticket Statistics by Status
SELECT
Status,
COUNT(*) AS TicketCount,
AVG(DATEDIFF(hour, CreatedAt, COALESCE(ResolvedAt, GETUTCDATE()))) AS AvgResolutionHours
FROM SupportTickets
WHERE CreatedAt >= @startDate
GROUP BY Status
ORDER BY TicketCount DESC
Parameters:
@startDate(DATETIME, required): Start date for statistics
Tool Description: "Get support ticket statistics grouped by status. Returns ticket counts and average resolution times. Use for reporting on support workload."
Security and Best Practices
Credential Protection
- All database passwords are encrypted at rest using AES-256-CBC encryption
- Credentials are never returned in API responses
- Connection test uses encrypted credentials directly
SQL Injection Prevention
SQL Query Tools use parameterized queries exclusively:
- All queries must use
@parametersyntax - Parameter values are escaped automatically
- Dynamic SQL is not allowed
- Suspicious patterns are blocked (DROP TABLE, xp_cmdshell, etc.)
Write Operation Safeguards
For queries that modify data:
- Connection-level control: Enable "Allow Write Operations" only when needed
- Query-level confirmation: Enable "Require Confirmation" for sensitive updates
- Audit logging: All write operations are logged with parameters and results
Result Size Limits
Three-tier limit system prevents excessive data retrieval:
- Connection Default: Applied to all queries using this connection
- Connection Absolute: Maximum rows that can ever be returned
- Query Override: Per-query limit (cannot exceed connection absolute)
Recommended Security Practices
- Least Privilege: Create dedicated database users with minimal permissions
- Read-Only by Default: Keep write operations disabled unless required
- Row Limits: Set appropriate limits to prevent accidental large result sets
- Audit Review: Regularly review query execution logs
- Parameter Validation: Use validation rules to constrain input values
Managing SQL Query Tools
View All Queries
Navigate to Build > Connections > SQL Tools > Queries to see all configured queries:
- Filter by connection
- Filter by query type (SELECT, UPDATE, etc.)
- Search by name or description
- View assigned agent count
Edit a Query
- Click the edit button on a query card
- Modify settings through the wizard steps
- Re-test the query before saving (required after changes)
- Save to update the tool
Delete a Query
- Click the delete button on a query card
- Confirm deletion
Deleting a query removes it from all agents that use it. Consider deactivating the query instead if you might need it later.
Toggle Active/Inactive
Use the status toggle to enable or disable a query without deleting it. Inactive queries are not available to agents.
Execution Logging
Viewing Query Executions
All SQL query executions are logged in the agent execution details:
- Navigate to Monitor > Activity > Agent Activity
- Click on an execution
- Expand the tool calls section
- Find the SQL query tool call
What Gets Logged
| Category | Details |
|---|---|
| Tool Call | Tool name, parameters passed |
| Execution | Start time, duration, success/failure |
| Results | Row count, sample data (truncated) |
| Errors | Error messages, SQL state codes |
Write Operation Audit
Write operations include additional audit data:
- Full parameter values
- Rows affected count
- Connection and database names
- User/agent that triggered the operation
Troubleshooting
Connection Errors
Problem: Cannot connect to database
Solutions:
- Verify server name and port are correct
- Check firewall rules allow Azure Functions access
- Verify credentials are correct
- For Azure SQL, ensure Azure AD login is configured if using AD auth
Query Timeout
Problem: Query exceeds command timeout
Solutions:
- Increase command timeout in connection settings
- Optimize the query (add indexes, reduce result set)
- Add more specific WHERE clauses to limit data
Parameter Type Mismatch
Problem: Query fails with type conversion error
Solutions:
- Verify parameter type matches column type
- Check parameter length for VARCHAR/NVARCHAR
- Ensure date formats are valid for DATETIME parameters
Tool Not Appearing
Problem: Query tool not available to agent
Solutions:
- Verify the query is Active (not disabled)
- Check the query is assigned to the agent
- Verify the connection is Active
- Refresh the agent's tool list
Empty Results
Problem: Query returns no results
Solutions:
- Verify test data exists in the database
- Check parameter values match expected format
- Test the query directly in SQL Server Management Studio
Related Topics
- Tools Overview - All available agent tools
- HTTP API Tools - Connect external REST APIs
- Agents - Configure agents to use tools
- Agent Executions - View tool execution logs