Web Analytics Made Easy - Statcounter
Home » SQL Server » How to Generate Embeddings and Store Them in SQL Server: Practical Examples

How to Generate Embeddings and Store Them in SQL Server: Practical Examples

Generate Embeddings And Store Them In Sql Server
How to Generate Embeddings and Store Them in SQL Server: Practical Examples

Introduction

Suppose your company has 100,000 customer support tickets, thousands of product descriptions, and hundreds of technical documents.

A customer asks:

“My application becomes slow whenever many users log in. Have we solved a similar problem before?”

A traditional SQL query might search for words such as slow, application, and users. But what if the previous support ticket says, “Response times increased during peak authentication traffic”?

The wording is different, but the meaning is similar.

This is where embeddings become useful.

Embeddings help applications find information based on meaning rather than relying only on exact keyword matches. When you combine embeddings with SQL Server, you can build solutions such as semantic search, intelligent knowledge bases, product recommendations, and retrieval-augmented generation (RAG).

In this article, we’ll walk through the process step by step, using practical examples that database developers and DBAs can understand.

1. What is an embedding?

An embedding is a numerical representation of text, an image, or another type of data.

For example, consider these three sentences:

  • “How can I improve SQL Server query performance?”
  • “My SQL query is running slowly.”
  • “What is the capital of France?”

The first two sentences have similar meanings. An embedding model attempts to represent that similarity in their numerical vectors. The third sentence should generally be less similar to the first two.

A simplified embedding might look like this:

Text

“My SQL query is running slowly.”

Embedding model converts text into numbers

Illustrative vector (not a real model output)

[0.12, -0.34, 0.78, 0.21, …]

A real embedding can contain hundreds or thousands of numbers, depending on the model.

These numbers are not manually assigned keywords. They are generated by a trained embedding model.

Please note: SQL Server stores and searches the resulting vectors. An embedding model generates them. You need to choose or build a process that connects these two activities.

2. How does the complete process work?

A typical embedding-based application follows this flow:

1. Source data

Support tickets, product descriptions, documents

2. Prepare the text

Clean, split into chunks, add identifiers

3. Generate embeddings

Call an embedding model

4. Store in SQL Server

Save text, metadata, and vector values

5. Search by meaning

Embed the question and find similar content

For example, a support team can use this process to find previously resolved incidents even when the customer describes the problem differently.

Let’s build the solution step by step.

3. What do you need before generating embeddings?

For this tutorial, we’ll use SQL Server 2025 (17.x), which introduces a native VECTOR data type and the AI_GENERATE_EMBEDDINGS function. The database engine can store vectors and, when configured with a supported external embedding model, generate them from text.

You have two main approaches.

ApproachHow it worksWhen to use it
Generate outside SQL ServerPython, an application, or an AI service generates embeddings and sends them to SQL ServerExisting AI pipelines or flexible model choices
Generate from T-SQLSQL Server calls a configured external model using AI_GENERATE_EMBEDDINGSDatabase-centric workflows and simpler integration

We’ll focus on SQL Server 2025’s native vector storage and embedding generation, then show how to store externally generated vectors too.

Before starting, make sure you have:

  • SQL Server 2025 or a supported Azure SQL environment.
  • A database and permission to create tables.
  • Access to a compatible embedding model.
  • The required external model configuration and credentials if generating embeddings through T-SQL.
  • A plan for matching the vector dimensions to the model’s output.

Important: The examples use a 1,536-dimensional vector for illustration. Your actual dimension count must match the embedding model you configure. Do not assume every model produces 1,536 values.

4. Create a sample database and table

Let’s use a realistic example: a company’s IT support knowledge base.

The support team has collected incidents such as:

  • SQL Server queries running slowly.
  • Failed database backups.
  • Login failures after password changes.
  • High CPU usage during business hours.
  • Transaction log files growing unexpectedly.

We want to search these incidents by meaning.

First, create a table to store the source text and its embedding.

CREATE TABLE dbo.SupportKnowledge
(
    KnowledgeID  INT IDENTITY(1,1) PRIMARY KEY,
    Title        NVARCHAR(200) NOT NULL,
    Content      NVARCHAR(MAX) NOT NULL,
    Category     NVARCHAR(100) NULL,
    CreatedAt    DATETIME2(0) NOT NULL
        CONSTRAINT DF_SupportKnowledge_CreatedAt
        DEFAULT SYSUTCDATETIME(),

    Embedding    VECTOR(1536) NULL
);
GO

Let’s understand the important columns.

  • KnowledgeID identifies each knowledge-base record.
  • Title contains a short description of the issue.
  • Content stores the detailed explanation or resolution.
  • Category allows normal SQL filtering.
  • Embedding stores the numerical representation of the text.

The embedding column is nullable because we may insert the source content first and generate its embedding later.

SQL Server’s VECTOR type stores vector values in an optimized binary format while exposing them in a JSON-array-like representation.

5. Insert some realistic support incidents

Let’s add sample data.

INSERT INTO dbo.SupportKnowledge
    (Title, Content, Category)
VALUES
(
    N'Slow SQL Server Queries',
    N'Queries are running slowly during peak hours.
      Check execution plans, logical reads, indexes,
      blocking, and Query Store before changing the query.',
    N'Performance'
),
(
    N'High CPU Utilization',
    N'SQL Server CPU usage remains high.
      Identify expensive queries, review execution plans,
      inspect waits, and check for recent plan changes.',
    N'Performance'
),
(
    N'Transaction Log Growing',
    N'The transaction log file keeps growing.
      Check the recovery model, log reuse wait description,
      transaction log backups, and long-running transactions.',
    N'Maintenance'
),
(
    N'Failed Database Backups',
    N'Database backups are failing.
      Review SQL Server Agent job history, backup destination
      permissions, available disk space, and error logs.',
    N'Backup'
),
(
    N'Application Login Failure',
    N'Users cannot connect to SQL Server.
      Check login status, authentication mode, permissions,
      connectivity, and relevant error messages.',
    N'Security'
);
GO

At this point, the table contains text but no embeddings.

SELECT
    KnowledgeID,
    Title,
    Category,
    Embedding
FROM dbo.SupportKnowledge;

The next step is to generate the numerical representation.

6. Configure an embedding model in SQL Server 2025

SQL Server’s AI_GENERATE_EMBEDDINGS function uses an external model definition registered in the database. The model definition tells SQL Server how to communicate with the embedding service.

The exact configuration depends on your model provider. For example, you might use a compatible Azure OpenAI embedding deployment or a supported local model endpoint.

The general setup involves:

  1. Configuring the database credential securely.
  2. Registering an external model using CREATE EXTERNAL MODEL.
  3. Ensuring the model’s output dimensions match your VECTOR column.
  4. Enabling outbound REST endpoint access where required.

On SQL Server 2025, outbound REST endpoint access must be enabled for this workflow. A DBA with the appropriate server-level permissions can configure it as follows:

EXECUTE sp_configure
    'external rest endpoint enabled', 1;
RECONFIGURE WITH OVERRIDE;
GO

Follow your organization’s security policies before enabling outbound access. Use Microsoft’s official setup documentation to configure the database master key, credential, endpoint, authentication, and model definition for your chosen provider.

The model-registration statement depends on the provider and its API configuration, so there is no single credential or endpoint statement that works unchanged for every environment.

Once your model has been registered under the name EmbeddingModel, the following examples show how to use it. Replace that name with the actual model identifier in your database.

7. Generate an embedding for a single sentence

Let’s start with a simple example.

A user asks:

“Why is my SQL Server query taking too long?”

We can generate an embedding for the sentence using T-SQL:

DECLARE @Question NVARCHAR(MAX) =
    N'Why is my SQL Server query taking too long?';

DECLARE @QuestionEmbedding VECTOR(1536);

SET @QuestionEmbedding =
    AI_GENERATE_EMBEDDINGS(
        @Question USE MODEL EmbeddingModel
    );

SELECT @QuestionEmbedding AS QuestionEmbedding;
GO

The function sends the input text to the configured embedding model and returns a vector.

The output contains numerical values rather than a human-readable explanation. The model is representing the text in a form suitable for similarity comparisons.

Remember: This example assumes that EmbeddingModel exists and returns exactly 1,536 dimensions. The code will not work until the model and its required connectivity have been configured.

8. Generate and store embeddings for all support records

Now let’s process our support knowledge base.

Instead of generating an embedding manually for every row, we can use an UPDATE statement.

UPDATE dbo.SupportKnowledge
SET Embedding =
    AI_GENERATE_EMBEDDINGS(
        Content USE MODEL EmbeddingModel
    )
WHERE Embedding IS NULL;
GO

This example illustrates batch processing within SQL Server. For a large production table, process records in controlled batches, monitor external model limits and failures, and avoid repeatedly embedding unchanged text.

Check the result:

SELECT
    KnowledgeID,
    Title,
    Category,
    CASE
        WHEN Embedding IS NULL THEN 'Pending'
        ELSE 'Generated'
    END AS EmbeddingStatus
FROM dbo.SupportKnowledge;

The table now contains both the original support content and its vector representation.

That is useful because the embedding remains associated with the record it describes. You can continue using ordinary SQL joins, permissions, filters, and metadata alongside vector operations.

9. Generate embeddings only for new or changed records

In production, you should not regenerate embeddings for every record whenever a new support ticket arrives.

Imagine you have 500,000 support articles. One new article is added. Regenerating all 500,000 embeddings would waste time and model calls.

A better approach is to generate embeddings for records that do not have one yet.

SELECT
    KnowledgeID,
    Title,
    Content
FROM dbo.SupportKnowledge
WHERE Embedding IS NULL;

You can process these records through a scheduled job or an application worker.

For updates, consider adding a ContentHash, EmbeddingModelVersion, and EmbeddingGeneratedAt column to track changes and model versions.

For example:

  • A new article needs an embedding.
  • An unchanged article can reuse its existing embedding.
  • An edited article needs a new embedding.
  • A model change may require regenerating embeddings to maintain consistency.

This is especially important when embedding generation involves an external service with usage limits or cost per request.

10. Search for similar support incidents

Now comes the interesting part.

Suppose a support engineer enters this question:

“SQL Server becomes slow when many users access the application.”

The question itself must be converted into an embedding using the same compatible embedding model used for the stored content.

DECLARE @Question NVARCHAR(MAX) =
    N'SQL Server becomes slow when many users access the application.';

DECLARE @QuestionEmbedding VECTOR(1536);

SET @QuestionEmbedding =
    AI_GENERATE_EMBEDDINGS(
        @Question USE MODEL EmbeddingModel
    );

SELECT TOP (5)
    KnowledgeID,
    Title,
    Category,
    VECTOR_DISTANCE(
        'cosine',
        @QuestionEmbedding,
        Embedding
    ) AS Distance
FROM dbo.SupportKnowledge
WHERE Embedding IS NOT NULL
ORDER BY Distance ASC;

VECTOR_DISTANCE calculates the distance between two vectors. With cosine distance, smaller values indicate greater similarity. The results are ranked by distance, so the closest matches appear first.

For example, the results might include:

Knowledge articleWhy it may match
High CPU UtilizationMany users can increase CPU demand
Slow SQL Server QueriesDirectly related to slow query execution
Transaction Log GrowingA possible contributing database issue

These are illustrative results, not measured outputs from the sample dataset. The actual ranking depends on the model and the text.

Notice that we never required the question to contain the exact phrase “high CPU utilization.” The embedding allows us to search for related meaning.

11. Example: Product recommendations for an e-commerce application

Embeddings are not limited to technical support.

Imagine an online store selling laptops, accessories, and computer equipment.

A customer views a product described as:

“Lightweight laptop suitable for software development and travel.”

The business wants to recommend products with similar characteristics.

First, create a table:

CREATE TABLE dbo.ProductCatalog
(
    ProductID  INT PRIMARY KEY,
    ProductName NVARCHAR(200) NOT NULL,
    Description NVARCHAR(MAX) NOT NULL,
    Embedding VECTOR(1536) NULL
);
GO

Insert sample products:

INSERT INTO dbo.ProductCatalog
    (ProductID, ProductName, Description)
VALUES
(
    101,
    N'Business Laptop',
    N'Lightweight laptop for business travel,
      office work, and software development.'
),
(
    102,
    N'Gaming Laptop',
    N'High-performance laptop with a powerful GPU
      for gaming and graphics-intensive workloads.'
),
(
    103,
    N'Portable Laptop',
    N'Compact laptop with long battery life
      for students and frequent travelers.'
),
(
    104,
    N'Workstation Laptop',
    N'Powerful mobile workstation for engineering,
      3D design, and demanding development workloads.'
);
GO

Generate embeddings for the product descriptions:

UPDATE dbo.ProductCatalog
SET Embedding =
    AI_GENERATE_EMBEDDINGS(
        Description USE MODEL EmbeddingModel
    )
WHERE Embedding IS NULL;
GO

Now, search for products similar to a portable development laptop:

DECLARE @SearchText NVARCHAR(MAX) =
    N'Portable laptop for software development
      with good battery life.';

DECLARE @SearchEmbedding VECTOR(1536);

SET @SearchEmbedding =
    AI_GENERATE_EMBEDDINGS(
        @SearchText USE MODEL EmbeddingModel
    );

SELECT TOP (3)
    ProductID,
    ProductName,
    VECTOR_DISTANCE(
        'cosine',
        @SearchEmbedding,
        Embedding
    ) AS Distance
FROM dbo.ProductCatalog
WHERE Embedding IS NOT NULL
ORDER BY Distance ASC;

The application can display the closest matches as recommendations.

Real-world benefit: You can combine semantic similarity with normal business rules. For example, use SQL predicates to filter out-of-stock products, exclude discontinued items, or restrict recommendations to a particular price range.

12. Example: Embeddings for long documents

What if your source data is not a short product description but a 100-page PDF, an employee handbook, or a technical manual?

Generating one embedding for an entire long document is often not the best approach.

Instead, split the document into smaller, meaningful chunks.

For example, an SQL Server troubleshooting guide might contain:

  • Chunk 1: Understanding high CPU usage.
  • Chunk 2: Identifying expensive queries.
  • Chunk 3: Reading execution plans.
  • Chunk 4: Investigating blocking.
  • Chunk 5: Applying and validating fixes.

Store each chunk separately, along with its document identifier and location.

SQL Server Troubleshooting Guide

Original document

Chunk 1

High CPU

Chunk 2

Expensive queries

Chunk 3

Execution plans

Chunk 4

Blocking and fixes

Generate and store an embedding for each chunk

SQL Server 2025 also provides AI_GENERATE_CHUNKS for splitting text into chunks. The exact chunking strategy should reflect the document structure and the limits of the selected embedding model.

A simplified table design might be:

CREATE TABLE dbo.DocumentChunks
(
    ChunkID      INT IDENTITY(1,1) PRIMARY KEY,
    DocumentID   INT NOT NULL,
    ChunkNumber  INT NOT NULL,
    ChunkText    NVARCHAR(MAX) NOT NULL,
    Embedding    VECTOR(1536) NULL
);
GO

You can then retrieve the most relevant chunks and provide them to a language model as context for answering a user’s question. This is one of the building blocks of retrieval-augmented generation (RAG).

For production use, also retain the original document name, access-control metadata, and source location so that answers can be traced back to their origin.

13. What if your embeddings are generated outside SQL Server?

You do not have to use AI_GENERATE_EMBEDDINGS.

Many organizations already generate embeddings through Python applications, Azure OpenAI, or another compatible model service.

In that case, the application sends the generated vector to SQL Server.

For example, suppose your application produces this small vector:

[0.12, -0.34, 0.78]

You can store it in a matching vector column:

CREATE TABLE dbo.ExternalEmbeddings
(
    ItemID INT PRIMARY KEY,
    ItemText NVARCHAR(500) NOT NULL,
    Embedding VECTOR(3) NOT NULL
);
GO

INSERT INTO dbo.ExternalEmbeddings
    (ItemID, ItemText, Embedding)
VALUES
    (1, N'Slow database query',
     '[0.12, -0.34, 0.78]');
GO

The three-dimensional vector here is a simplified demonstration, not a useful production embedding model.

For real embeddings, use the actual output dimensions of your selected model and insert the vector using a parameterized database command. Do not concatenate untrusted text or vector payloads directly into dynamic SQL.

The main advantage of this approach is flexibility: your application can manage model selection and embedding generation while SQL Server manages the associated data and similarity queries.

14. Best practices for storing embeddings

Here are the practices I would recommend before deploying an embedding-based application.

1. Keep the original text

Store the source text and its embedding together, or retain a reliable reference to the original record. An embedding is not a replacement for the original content.

2. Match the vector dimensions

The declared VECTOR(n) dimension must match the number of values generated by your model. SQL Server rejects vectors with the wrong number of dimensions.

3. Use a consistent embedding model

Query embeddings and stored embeddings should come from compatible model configurations. If you change models, plan how to regenerate existing embeddings and avoid mixing incompatible vector spaces.

4. Process large datasets in batches

Avoid generating millions of embeddings in one uncontrolled transaction. Monitor model throttling, failures, execution duration, and transaction-log growth.

5. Track changes and model versions

Store a content hash, model identifier, and generation timestamp. This helps identify stale embeddings and plan reprocessing when content or model configuration changes.

6. Apply access controls to retrieved content

Semantic search must not bypass normal authorization. Filter results according to the user’s permissions and the source document’s access rules.

7. Measure retrieval quality

Test the results with realistic questions. Compare the retrieved records against known relevant answers rather than assuming that the lowest distance always means the best business result.

15. Common mistakes to avoid

MistakeWhy it matters
Treating an embedding as a keyword listEmbeddings represent learned features and semantic relationships, not a list of searchable words.
Using a vector column with the wrong dimensionsThe insert or conversion will fail.
Generating an embedding for every query repeatedly when it can be reusedIncreases latency and may increase model usage costs.
Embedding an entire large document without considering chunkingImportant details can become difficult to retrieve precisely.
Changing the embedding model without a migration planStored vectors and query vectors may no longer be comparable.
Assuming semantic search always returns the correct answerSimilarity ranking is not a guarantee of factual correctness.
Forgetting source permissionsSearch results could expose content a user is not allowed to access.

16. Do you need a vector index immediately?

Not necessarily.

Start by storing embeddings and validating your search results on a manageable dataset. Exact similarity queries using VECTOR_DISTANCE are useful for initial development and quality checks.

As the dataset grows, evaluate vector indexing and approximate nearest-neighbor search to improve retrieval performance. SQL Server 2025 provides native vector-index capabilities, but feature prerequisites and availability should be checked for the exact build and environment you use.

Do not create a vector index simply because the feature exists. Measure query latency, recall, resource use, and the quality of the returned results first.

17. Final takeaway

Generating embeddings and storing them in SQL Server becomes much easier once you separate the process into three responsibilities:

  1. Generate: Convert text into vectors using a compatible embedding model.
  2. Store: Save vectors alongside the original content and its metadata.
  3. Retrieve: Embed the user’s question and compare it with stored vectors to find relevant records.

Whether you are building an IT support knowledge base, product recommendations, or a document-search solution, the same principles apply.

SQL Server 2025 brings vector storage and embedding-generation capabilities into the database workflow, allowing developers to combine semantic retrieval with traditional relational data.

The most important lesson is that embeddings are only one part of a successful AI application. Good source data, appropriate chunking, consistent models, correct access controls, and measured retrieval quality are equally important.


Discover more from Technology with Vivek Johari

Subscribe to get the latest posts sent to your email.

Leave a Reply

Scroll to Top

Discover more from Technology with Vivek Johari

Subscribe now to keep reading and get access to the full archive.

Continue reading