Category Archives: SQL Server

How to share SQL query result to C# on Polyglot Notebook?

Polyglot Notebook has an interesting feature that can share SQL query results directly from SQL to C#, this makes it useful as a scratchpad. The example code is below.

Cell 1 – Add NuGet packages for Polyglot, TabularDataResource, and DataFrame

#r "nuget: Microsoft.DotNet.Interactive.SqlServer, *-*"
#r "nuget: Microsoft.Data.Analysis"

Cell 2 – Connect to SQL Server and WideWorldImporters sample DB

#!connect mssql --kernel-name myDb1 "Server=(localdb)\LocalDB2025;Database=WideWorldImporters;Trusted_Connection=True;TrustServerCertificate=True;"

Cell 3 – Run the queries and set to customerData variable

#!sql-myDb1 --name customersData
SELECT TOP 3 *
FROM Sales.Customers WHERE CustomerName LIKE '%Toys%'

SELECT TOP 3 *
FROM Sales.Customers WHERE CustomerName NOT LIKE '%Toys%'

Cell 4 – Share to C# customerData

#!share --from sql-myDb1 customersData

foreach (var data in customersData)
{
    "Table".Display();
    foreach (IEnumerable<KeyValuePair<string, object>> row in data.Data)
    {
        // Row is a list instead of dictionary, need to search if want to display by column ID, e.g.
        // row.FirstOrDefault(x => x.Key == "CustomerID").Value.Display();
        
        foreach (KeyValuePair<string, object> field in row)
        {
            Console.Write($"{field.Key}: {field.Value} | ");
        }
        Console.WriteLine();
    }
}

Cell 5 – Another example of sharing customersData2 variable from SQL to C#

#!sql-myDb1 --name customersData2
SELECT TOP 3 CustomerID, CustomerName, BillToCustomerID, CustomerCategoryID, BuyingGroupID, PrimaryContactPersonID, AlternateContactPersonID, DeliveryMethodID, DeliveryCityID, PostalCityID, CreditLimit, CAST(AccountOpenedDate AS NVARCHAR(20)) AccountOpenedDate
FROM Sales.Customers WHERE CustomerName LIKE '%Toys%'

#!C#
#!share --from sql-myDb1 customersData2
var df = customersData2[0].ToDataFrame();
df.Display();

// If want to convert to DataTable
// df.ToTable().Display();

foreach (Microsoft.Data.Analysis.DataFrameRow row in df.Rows)
{
    // Access by column Name
    // row["CustomerID"].Display();
    
    for (int i = 0; i < df.Columns.Count; i++)
    {
        Console.Write($"{df.Columns[i].Name}: {row[i]} | ");
    }
    Console.WriteLine();
}

Note: The AccountOpenedDate column needs to be cast to nvarchar due to an error (Error: System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values. at Microsoft.DotNet.Interactive.Formatting.TabularData.TabularDataResourceExtensions.ToDataFrame(TabularDataResource tabularDataResource)) in ToDataFrame(), so a workaround has been used.

How to use EF Core and Create the DBContext on Polyglot Notebook?

To use EF Core for a SQL Server DB on Polyglot Notebook, we normally need to reference an EF Core library in order to use it. But besides that, Polyglot Notebook is able to auto generate the DB Context from the database itself. Just follow the steps below.

Cell 1

#r "nuget: Microsoft.DotNet.Interactive.SqlServer, *-*"
// In normal case, you don't need Microsoft.Identity.Client, but due to an error (Error: Microsoft.Identity.Client version 4.66.2 cannot be added because version 4.66.1 was added previously.), it needs to be specified manually. 
#r "nuget: Microsoft.Identity.Client, 4.66.2"
// This use to display the output in Polyglot, which might not be required depending on your own use cases.
#r "nuget: Microsoft.Data.Analysis"

Cell 2

// Connect to SQL Server and create the DB Context as Wwi
#!connect mssql --create-dbcontext --kernel-name Wwi "Server=(localdb)\LocalDB2025;Database=WideWorldImporters;Trusted_Connection=True;TrustServerCertificate=True;"
var context = new WwiContext();
var customers = context.Customers.Where(c => c.CustomerId < 1000)
    .Skip(1).Take(3).ToList();
display(customers.ToTabularDataResource());

Sample Output

Command to Create a New Instance of SQL Server LocalDB

To create a new instance of Microsoft SQL Server LocalDB after you already have default (localdb)\MSSQLLocalDB, you need to make sure the localdb command-line tool is accessible.

First, start a PowerShell on Windows and type the command below to check; it will show the Microsoft (R) SQL Server Express LocalDB Command Line Tool help.

sqllocaldb -?

Then, use the commands below to create the new instance of localdb using the latest version of localdb in your computer (use sqllocaldb v if you want to check how many versions of localdb in your computer).

# LocalDB2025 is the instance name, you might want to change to different name
sqllocaldb c LocalDB2025

# Show the info of newly created instance
sqllocaldb i LocalDB2025

# Start the new instance
sqllocaldb s LocalDB2025

That’s all the commands, and now you can connect to the new instance using (localdb)\LocalDB2025.

Creation of LocalDB instance “mssqllocaldb” failed because of the following error: Error occurred during LocalDB instance startup: SQL Server process failed to start.

If you have the error above during SQL Server LocalDB creation or starting, it might due to strange behavior on several versions of SQL Server, including SQL Server 2022. 

First, try to recreate the LocalDB instance first if you are using LocalDB.

sqllocaldb stop MSSQLLocalDB
sqllocaldb delete MSSQLLocalDB
sqllocaldb create MSSQLLocalDB
sqllocaldb start MSSQLLocalDB

If still getting the same error, check the error log for the SQL Server which located at below.

%LocalAppData%\Microsoft\Microsoft SQL Server Local DB\Instances\mssqllocaldb

Inspect the last few lines of the error, you might get the error below.

2025-06-08 21:37:49.09 spid10s     There have been 256 misaligned log IOs which required falling back to synchronous IO.  The current IO is on file C:\Users\xxxx\AppData\Local\Microsoft\Microsoft SQL Server Local DB\Instances\mssqllocaldb\master.mdf.

If that is the error you have, you might need to add ForcedPhysicalSectorSizeInBytes to your Computer\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\stornvme\Parameters\Device registry. Please head to Troubleshoot errors related to system disk sector size greater than 4 KB for Microsoft official resolution. 

Reference: 

New AI Search function in SQL Server 2025 Preview

SQL Server 2025 Preview has added a new AI vector search feature, developers now can you semantic or natural language to search their own data instead of just SQL script such as LIKE syntax. This should be a very convenient thing for developers, though it requires some setup. Please watch the video for details. 

Repost from https://mycsharpdeveloper.blogspot.com/2025/06/new-ai-search-function-in-sql-server.html

SQL Server 2025 Incorrect syntax near ‘=’ for AI_GENERATE_CHUNKS

If you get the error below on SQL Server 2025 for AI_GENERATE_CHUNKS AI functions, please make sure your database compatibility level is in SQL Server 2025 version.

Msg 102, Level 15, State 38, Line 8
Incorrect syntax near '='.

Completion time: 2025-05-30T16:50:52.0246402+08:00

You can set the DB compatibility level by right-click the DB > click the Properties menu > Options tab > Compatibility level.

Repost from https://mycsharpdeveloper.blogspot.com/2025/05/sql-server-2025-incorrect-syntax-near.html