r/SQLServer 1d ago

Discussion September 2026 | "What are you working on?"

10 Upvotes

Welcome to the open thread for r/SQLServer members!

This is your space to share what you’re working on, compare notes, offer feedback, or simply lurk and soak it all in - whether it’s a new project, a feature you’re exploring, or something you just launched and are proud of (yes, humble brags are encouraged!).

It doesn’t have to be polished or perfect. This thread is for the in-progress, the “I can’t believe I got it to work,” and the “I’m still figuring it out.”

So, what are you working on this month?

---

Want to help shape the future of SQL Server? Join the SQL User Panel and share your feedback directly with the team!


r/SQLServer 2d ago

Discussion September 2026 | Job Opportunities

4 Upvotes

Welcome to the monthly job thread!

Posting a job or opportunity? Include:

  • Role title and description
  • Location or remote/hybrid status
  • Company or client context
  • Direct application link

Looking for work? Share your skills, experience level, and what you're looking for.

Rules:

  • One top-level comment per opportunity
  • No "DM me" or link-free posts — include a direct, verifiable link
  • Scam or misleading comments will be removed and may result in a ban

r/SQLServer 5h ago

Question I deleted the database and it has no backup

8 Upvotes

Hi , I deleted a database by mistake how can i restore it ? What software should i use?


r/SQLServer 15h ago

Discussion 1 year in as a DBA — does the "there's always something I don't know" anxiety ever go away?

33 Upvotes

Hi everyone,

I'm about a year into my career as a DBA, managing a fairly large SQL Server environment — multiple production and dev/test instances, hundreds of databases, several Always On Availability Groups. I wanted to ask the more experienced folks here about something that's been weighing on me.

I have this drive to master literally everything about the job. Every time I feel like I've got a solid handle on things, I discover something new that other DBAs already seem to know. A few months in, I only just found out how much Extended Events could do for me. Not long after that, I realized how much I hadn't explored in the SQL Server Error Logs. It feels like there's always another layer, and every time I find a gap in my knowledge, it genuinely stresses me out — I start worrying there's some critical thing I still don't know that could cause an incident I won't be able to solve.

This worry gets worse when I think about the future. I've had a referral and interest from a recruiter for another DBA role, and one real possibility is being the only DBA at a company, with no senior DBA to lean on. That idea makes me anxious, because I still feel like I'm learning.

One specific moment really shook me: we had an issue on two servers that were part of an Availability Group, and we ended up doing a server-level restore. After the restore, when I went to open the databases, both servers showed the AG state as "Resolving." In the middle of an active incident, with everyone waiting for a fix, I panicked — I didn't fully understand why it was happening, and I felt too much pressure to admit I wasn't sure. A colleague eventually stepped in and resolved it. That moment stuck with me — both the technical gap and the fear of not looking capable under pressure.

So, a few questions for this community:

- Is there a specific learning path or series of resources that, if I go through it start to finish, would actually give me solid, well-rounded coverage of everything a SQL Server DBA needs to know? Or is that just not how it works?
- Is this "there's always something new" feeling something every DBA goes through, even years in, or does it fade?
- How did you build the confidence to stay calm during a crisis even when you don't immediately know the answer?
- Any resources, checklists, or hard-earned lessons about AG "Resolving" states or post-restore health checks that you wish you'd known earlier?
- For anyone who's been the sole DBA at a company — what do you wish you'd known before taking that on?

Would really appreciate any perspective — even just "yeah, that's normal, it gets better." Thanks in advance!


r/SQLServer 16h ago

Community Share SSMA 10.6 released — Code Conversion Copilot now GA for Sybase, Managed Endpoint auth GA

Thumbnail
techcommunity.microsoft.com
2 Upvotes

Disclosure: I'm a PM on the SQL migration tooling team at Microsoft. Posting because a couple of these affects anyone already using SSMA's Copilot features.

  • Code Conversion Copilot is GA for Sybase — was preview, now supported for production work.
  • Managed Endpoint auth is GA — no Azure OpenAI resource to stand up. BYOK still available.
  • Managed Endpoint now has usage limits: 16k tokens per source script, 2k per prompt, 15 req/min and 7,200 per 8 hours per customer, 75 req/min aggregate. Interactive use won't hit these; for bulk work, BYOK is bounded by your own quota instead.
  • BYOK model list changed (Oracle + Sybase): now gpt-4.1, gpt-5.4-mini, gpt-5.5, gpt-5.6-terra. gpt-5.4 removed — reconfigure if that's what you're on.
  • Fix: DMS auth failures when multiple Azure subscriptions share the same display name.

Full writeup: in the blog

Happy to answer questions. If conversion output goes wrong in an interesting way, I'd like to hear about it.


r/SQLServer 18h ago

Question SQL Server 2022 Standard to Enterprise in Azure VM

4 Upvotes

I'm planning an in-place edition upgrade from SQL Server 2022 Standard -> Enterprise on a standalone Windows Azure VM.

The reason is that we need to move beyond Standard's CPU/memory limitations.

The Microsoft-documented process is essentially:

  1. Remove the SQL IaaS Agent registration
  2. Run SQL Server Setup -> Maintenance -> Edition Upgrade -> Enterprise
  3. Validate SQL
  4. Re-register the SQL IaaS Agent / update the Azure SQL VM edition

Microsoft says the edition upgrade is supported in-place and restarts the SQL Server service.

For anyone who's actually done this:

  • What should I expect during the Edition Upgrade?
  • Will Setup ask for an Enterprise product key, or does Azure PAYG/IaaS handle the licensing side?
  • Any common failure points or gotchas?
  • Is this generally as straightforward as Microsoft makes it sound?
  • Anything you'd specifically check before doing this on a production VM?

It's a standalone SQL instance (not an AG/cluster).

Thanks!


r/SQLServer 1d ago

Question SSMS client Workspace relocation assistance

2 Upvotes

Is there a way to use Microsoft SQL Server management Studio 22 without it writing anything at all (no folders, shortcuts, junctions, symbolic links) in My Documents? I just installed the latest client from the official website on my Windows 11 laptop without launching the client yet, and I want the SSMS workspace (configuration files, data files, etc.) to be transferred to a different location in the C drive. I failed in my first try, and both Claude and Gemini gave me conflicting answers.

To summarize, I don't want the folders below or anytrhing related to it appearing inside My Documents.

C:\<My Dopcuments Folder path>\SQL Server Management Studio

C:\<My Dopcuments Folder path>\SQL Server Management Studio 22


r/SQLServer 2d ago

Community Share I finally built the SQL Server Feature Matrix I've wanted for years -- SQL.FM

Post image
18 Upvotes

About six years ago, Brent Ozar linked to the PostgreSQL Feature Matrix in his newsletter and wrote, "I wish we had this for SQL Server."

I remember seeing that and thinking the same thing. I'd wanted an easier way to answer questions like: When did SQL Server get this feature? Which versions and editions support it? What about Azure?

I never really had the time to build a comprehensive feature matrix until this year, when I had some free nights and weekends to devote to the project.

So, I finally built one for SQL Server -- and it's completely free to use:

SQL Server Feature Matrix (SQL.FM)
https://sql.fm

The Feature Matrix currently tracks 300+ SQL Server features across versions going all the way back to SQL Server 1.0, including edition differences, Azure SQL Database, and Azure SQL Managed Instance.

You can choose exactly which versions/environments you want to compare, search for individual features, and use a “Hide unchanged features” checkbox to quickly narrow the matrix down to the differences.

While building it, I ended up adding three other quick references I often find myself looking for:

  • SQL Server Version Reference
  • SQL Server & OS Compatibility Matrix
  • Date & Time Reference

A significant part of the project was researching and verifying the feature data, especially for the older SQL Server releases. I spent a lot of time digging through Microsoft documentation, archived material, and other historical sources, and I've tried to be as accurate as possible.

That said, with hundreds of features spanning decades of SQL Server releases, there's always the possibility that something slipped through. If you find an error, have a better source for something, or notice a feature that's missing, I'd really appreciate the feedback.

I built this because it's the kind of reference I've wanted to have myself, so hopefully some of you find it useful too.


r/SQLServer 2d ago

Question Archive data in SQL Server – best way to move old logs without killing performance

6 Upvotes

Hey all,

We've got a bunch of systems writing logs into SQL Server tables, and the main log table has crept up to ~16 million rows. Every few weeks someone runs a DELETE to trim it down, and the whole server stutters for like 20 minutes. Not fun.

The catch: we can't just delete the old rows. We need to move them to an archive table so we still have access to them if something blows up and we need to go back and dig.

I've been trying a basic INSERT INTO archive SELECT ... FROM logs WHERE date < X followed by a DELETE, but even that's slow at this scale and locks things up.

What I'm looking for:

Is there a better pattern for this? (batching, partitioning, something else I'm not thinking of?)

Any gotchas I should know about before I set this up as a recurring job?

Does anyone have a solid stored procedure or script they've used for this in production?

Happy to share schema / stats if that helps. Basically I just want to stop the "why is everything slow" Slack messages every two weeks.

Thanks in advance.


r/SQLServer 2d ago

Question OLE DB driver 19.4.2 & ODBC driver 18.6.2.1 conflict with authentication stack?

4 Upvotes

Hi,

Sorry if this is the wrong spot to post, if it is feel free to delete. I don't normally post but currently working through an issue I'm stumped on and don't seem have any support entitlements through the MS engage center. I'm not the most knowledgeable with SQL so its been a learn as I go with copilot's help.

I'm troubleshooting an Excel VBA (ADODB) workload that is stable with OLE DB 19.3.7 + Authentication=ActiveDirectoryInteractive, but consistently crashes with OLE DB 19.4.1/19.4.2 using Integrated, Password, or Interactive authentication. The crashes begin to occur only after the ODBC driver is installed, prior to installing it works as expected. Initial run of the macro works every time, then after 7-15 minutes when running the macro again to refresh the data it crashes. After uninstalling the ODBC driver and/or reinstalling the OLE DB Driver the issue persists.

Event viewer shows 2 different errors, 1 faulting module path C:\WINDOWS\SYSTEM32\ntdll.dll and the other pointing to mssql-auth.dll_unloaded WinDbg shows repeated crashes caused by a stale callback into an unloaded mssql-auth.dll module. The callback target consistently resolves to mssql-auth.dll+0x336db0.

Have tried numerous uninstall/reinstalls, different driver versions, different authentication types in the macro but nothing else seems to work. I'm able to replicate the issue on multiple devices.

Windows 11 25H2

Excel 365

OLE DB Driver 19.4.2

ODBC Driver 18.6.2.1

Thanks,

J


r/SQLServer 3d ago

Discussion Thoughts on dbForge over SSMS

0 Upvotes

Been on SSMS since about 2012. Started using dbForge Studio properly a year ago and I have opinions, curious where other people have landed.

To be clear, SSMS got better. 22 being 64-bit on the VS shell killed the out of memory nonsense on large result sets, dark theme finally exists, Copilot is in there if you want it. It is free, it is what everyone has, and if you administer servers it is still the thing. I am not arguing anyone should uninstall it.

Where dbForge wins for me is everything around writing the query rather than the query itself.

Comparison, mainly. Schema and data compare are built in and they generate sync scripts you can read before you run them. In SSMS world you are either buying Redgate, working with SqlPackage and DACPACs, or doing it by hand. Redgate is excellent and also costs considerably more. This is the actual reason I switched.

The editor is the other one. Native IntelliSense is still weak, it gets confused by aliases and CTEs and gives up on bigger schemas. dbForge completion is better and the formatting is properly configurable, which matters if a team wants to share one profile. Worth saying you can get exactly that inside SSMS with dbForge SQL Complete as an add-in, same engine, so if you like SSMS and only want the editor fixed, that is the cheaper path. Took them a few months to support SSMS 22 but it is there now.

Little things that matter. Test data generation that gives values that a human would expect. Documentation that you can actually generate instead of promising to write. Unit testing on tSQLt without having to set up the framework yourself. Source control integration that doesn’t hurt.

The downsides... It is a paid product, licensed per engine, and Edge if you want all of them. SSMS will always be more current for brand new SQL Server features because Microsoft ships it. Some of the DBA surface is thinner, I still keep SSMS for Agent jobs, Always On and anything security related. The UI is dense, a lot of toolbars, it is not a minimal app. And if your shop is standardized on SSMS you will be the one person handing off scripts with your own formatting on them.

Where I have landed is both. dbForge for development, SSMS for administration. Less clean than I would like, works fine.

What I want to know is whether anyone has gone fully off SSMS, or if everyone is running the same split I am.


r/SQLServer 3d ago

Community Share FabricPrep.com - Opensource Initiation to Mock Exams - Feedback

Thumbnail
1 Upvotes

r/SQLServer 3d ago

Community Share SQL Server has no pg_dump, so I wrote one - a CLI that dumps schema + data to a readable archive

8 Upvotes

Coming from Postgres, the thing I missed most in SQL Server was pg_dump: one command, schema and data, into a file I can actually read.

The nearest equivalent is a .bacpac, which comes closer than I first gave it credit for — /p:TableData lets you pick which tables' data to include — but the subsetting stops there: no row-level filtering, always the full schema, and the contents are opaque (model.xml plus BCP binary). So I wrote a small Go CLI that does what I wanted. MIT licensed, free, nothing to sell.

What it does

  • Exports schema and data into a zip: a JSON manifest, the DDL as plain runnable .sql, and one JSONL file per table. You can grep it, diff two of them, or read the DDL before restoring anything.
  • Restores into another database. A verify command then compares the restored database against the archive and reports whether every table matches.
  • Filters: --where per table, --exclude-data to keep a table's definition but drop its rows, --include and --exclude. Foreign keys pointing at a partially held table are created WITH NOCHECK, and it says so loudly.
  • Resumable. Kill it at 90% and --resume carries on from the work directory.

Numbers - same machine, same database, 403 tables / 681,357 rows / 742 MB, local SQL Server 2025:

Export     dbdumper 11 s      Data-tier Application 57 s
Restore    dbdumper 22 s      Data-tier Application 81 s

It reads tables concurrently, splits a large table into key ranges read in parallel, and splices already-compressed streams into the zip instead of recompressing them.

What it is not

  • Not a backup. No point-in-time recovery. If BACKUP and RESTORE are available to you, they are faster and lose nothing.
  • Not transactionally consistent. Each table is read in its own statement, so rows in one table can be newer than another's. Snapshot the database first if that matters.
  • No users, roles or permissions. A bacpac does carry database users and roles, but not the server logins behind them, so they arrive orphaned - dbatools Export-DbaLogin and Export-DbaUser are the right tools there.
  • For pulling a large database out of Azure SQL wholesale, a server-side bacpac still wins: the extract never crosses your connection.

One bug worth flagging in case it bites you elsewhere: SQL Server 2025 vector columns broke restores entirely until yesterday. sys.types reports the vector system type as varbinary, so the generated DDL came out without a dimension count and the server rejected it with "Cannot find data type vector", which reads as though the type were unsupported rather than incompletely written. Fixed in v0.1.1.

https://github.com/JeePeeTee/dbdumper

I would genuinely like to know where it breaks on a database that isn't mine.

Edit: corrected the bacpac description — /p:TableData does allow table-level data selection; thanks to the commenter who pointed it out.


r/SQLServer 3d ago

Question no certificate validation on startup?

2 Upvotes

We have made an observation regarding SQL Server 2025.
There is an expired certificate on the server that is also configured within SQL Server.
The SQL Server log indicates that the certificate was read successfully.

The question is: Does SQL Server not check whether the certificate is valid during startup?
The documentation is a bit unclear on this point: https://learn.microsoft.com/en-us/sql/database-engine/configure-windows/certificate-requirements?view=sql-server-ver17


r/SQLServer 5d ago

Discussion The generic ASK_AI (see earlier post) can be implemented in your own data apps too!

Thumbnail
gallery
0 Upvotes

ASK_IA is built with vanilla T-SQL stored procedures inside SQL Server 2025. See earlier posts.

But it proved even more useful when it was implemented inside an APP. Here in this app, it builds BUTTONS on the fly! I made sure it can only generate the button and I created no tool to execute it in order to avoid it to go rogue . So ONLY a real user can click it.

How are you building this kind of agentic functionality with SQL Server 2025?


r/SQLServer 6d ago

Question Erro 20534

Post image
0 Upvotes

alguém já pegou esse erro no ODBC ele usa o SQL server


r/SQLServer 6d ago

Community Share mssql-python took 11.87s where pyodbc took 0.77s, so we moved parameter binding into C++

13 Upvotes

It's Friday and that means another mssql-python release.

The most exciting thing this time around is performance work in response to a community report.

While working on SQLAlchemy integration, GitHub user dxdc found that the driver's many-parameter execute() path was much slower than pyodbc. SQLAlchemy 2.x generates batched insertmanyvalues statements close to SQL Server's 2,100 parameter limit.

Their repro used about 2,098 parameters per call and measured this:

mssql-python: 11.87s (8,427 rows/s)
pyodbc:         0.77s (130,000 rows/s)

They gave us runnable code, timings, package versions, and the workload that exposed the problem. I love this part of open source. A useful report can change the driver for everyone who installs the next version.

For every parameterized execute(), the driver has to inspect each Python value, choose its SQL and C types, bind it, and call SQLExecute. We were detecting those types in a Python loop, constructing a ParamInfo object per parameter, and carrying those objects across the pybind11 boundary into C++.

That is now one native C++ pipeline. Parameter detection, binding, and execution happen in a single Python-to-native call, and the metadata stays in C++.

The isolated type-detection benchmark went from 2.0 to 2.3 microseconds per parameter to about 35 nanoseconds. That is roughly 60x for the detection step itself. Whole insert workloads on macOS ARM64 looked like this:

Workload Before After Speedup
Orders: integer, varchar, decimal, datetime2 880.6 ms 561.0 ms 1.57x
Events: UUID, datetime2, varchar, integer 827.2 ms 533.5 ms 1.55x
Documents: nvarchar(max) around 10 KB 1622.0 ms 1021.3 ms 1.59x
Wide rows: 50 mixed columns 1598.6 ms 1048.9 ms 1.52x

Those are not scientific measurements and definitely not a throughput guarantee. The gain scales with the amount of parameter work in each call.

How you code still matters too. A test issuing 5,000 single-row calls with four parameters showed no meaningful change because the network round trip dominated. Calls using setinputsizes() also retain the old path for now because their explicit type overrides need to be honored. Issue #500 remains open while that work continues.

There is also an executemany() Decimal conversion failure included the entire parameter row in the exception. If your application sent tracebacks to Splunk, Sentry, Application Insights, or another APM system, names, emails, balances, or other values in that row could go with it.

The new error contains only metadata:

Failed to convert parameter to Decimal at row 0, column 3 (value type: str)

We also suppressed value-bearing exception causes so the data cannot reappear through a chained traceback.

One upgrade detail: connect(timeout=N) now does what its documentation has always said. It bounds the login attempt. It used to become the query timeout instead, so it could fail to stop a slow connection and later cancel a long-running query. Set conn.timeout = N explicitly if you want a per-statement query timeout.

Also in 1.14.0: Polars string_view columns work directly with bulkcopy_arrow(), Arrow fetch errors are no longer hidden by cleanup errors, bulkcopy(timeout=0) means no timeout, and x64 Python loads the correct extension on Windows ARM64 hosts.

pip install --upgrade mssql-python

Full writeup: https://techcommunity.microsoft.com/blog/sqlserver/mssql-python-1-14-0-faster-parameter-binding-safer-errors-correct-timeouts/4551366

Code and benchmark details: https://github.com/microsoft/mssql-python/pull/549

Original community report: https://github.com/microsoft/mssql-python/issues/500

Repo: https://github.com/microsoft/mssql-python

I would love to see your before-and-after numbers from real wide-row or batched workloads. Please comment below with your rough statement shape, batch size, client and server locations, and Python version so we can understand what moved.


r/SQLServer 6d ago

Question Cost of backing sql db running on vm using azure backup.

1 Upvotes

Hi

I have a few sql servers running on azure vm. There are standalone instances and sql ag.

I want to know what is the cost involved if I want to backup the db on these instances via azure backup.

Would appreciate any tips and suggestions to optimise cost


r/SQLServer 7d ago

Question Is listing exact infrastructure numbers on my resume oversharing?

7 Upvotes

I work as a DBA at a government organization and wanted to get some perspective from people more experienced in the field.

Im considering adding this line to my resume under experience:

Administer 81 SQL Server instances (62 production, 19 dev/test) hosting 847 databases across 10 Always On Availability Group systems

Two questions:

**1.**  Is it normal/fine to include specific numbers like this on a resume? Also, does the dev/test to production ratio here suggest an actual environment issue, or is this typical for organizations of a certain size?  
**2.**  Do you think numbers at this level of precision count as sensitive information that shouldn**’**t be shared — even in a resume sent directly to companies/recruiters who request it?

Would appreciate any experience or insight, especially from anyone whos worked in similar-scale environments.


r/SQLServer 7d ago

Question How does SQL Server Standard Server + CAL licensing work for an on-prem ERP?

2 Upvotes

I'm an IT Manager at a company and currently we have an ERP system running on SQL Server 2008 Express on Windows Server 2008. The ERP application is .NET-based.

We're planning to migrate to:

  • Windows Server 2025
  • SQL Server 2025 Standard
  • New physical server with 12 cores
  • Around 30+ ERP users

We want Standard mainly because we need features such as SQL Server Agent and CDC, which aren't available in Express.

When I checked SQL Server licensing, the per-core model looks very expensive for our 12-core server.

One local Microsoft partner has offered this:

for approximately 3,500 QAR (~$960 USD).

My understanding is that this is the Server license for the Server + CAL model, meaning we would then need SQL Server CALs for each ERP user/device accessing SQL Server.

With 30+ users, would Server + CAL generally make more sense than licensing all 12 cores?

Are there any licensing or technical issues I should be aware of with this setup, especially since the ERP application is an older .NET application?

Thanks!


r/SQLServer 8d ago

Community Share SQL DB inernals

0 Upvotes

Hi, I am new to this team. I have you tube shorts link as below for sql db internals. Basically I had created it for myself for a quick fo through the internals which is always with me to scroll anywhere on my mobile. I need your valuable feedback on this if you can spare some time to make it better for others as well.

https://www.youtube.com/@SQLDBAInterview


r/SQLServer 8d ago

Community Share Make your SQL Server 2025 capable to talk to you!

Post image
0 Upvotes

dbo.sp_ask_ai — technical description

Purpose

sp_ask_ai is a synchronous T-SQL wrapper around the async ask_ai chat pipeline. It lets a caller in plain SQL — SSMS, sqlcmd, an Agent job, a bench script — submit a question, wait for the reply, and get back both: - the assistant’s answer- metadata about the run: status, elapsed time, step count, cost, tools used, chat/run IDs

It exists because the underlying post mechanism, sp_openai_chat_post, only returns a reply id and the answer arrives later through Service Broker activation. This procedure centralizes the polling, validation, and reporting logic that otherwise had to be reimplemented by every caller.

Source: tracy_fka_proj.dbo.sp_ask_ai definition in sys.sql_modules


Signature

```sql

-- Name: TSQL.APP

-- Auhor: RH

CREATE PROCEDURE dbo.sp_ask_ai @q nvarchar(max) = NULL, @thread nvarchar(100) = NULL, @new bit = 0, @wait_s int = 300, @card nvarchar(128) = NULL, @record_id int = NULL, @quiet bit = 0, @throw bit = 1, @user_name nvarchar(256) = NULL, @answer nvarchar(max) = NULL OUTPUT, @chat_id int = NULL OUTPUT ```


High-level behavior

The procedure does five things: 1. Validates the environment - question is not empty - not inside an explicit transaction - Service Broker is enabled - the openai_chat_queue queue exists, can receive, and has activation enabled - API key is configured when it can be checked 2. Resolves caller identity and thread - uses @user_name or SUSER_SNAME() - defaults thread to ssms:<user> 3. Posts the request - calls dbo.sp_openai_chat_post - captures the resulting @chat_id 4. Polls for completion - waits up to @wait_s - reads dbo.agent_chat for status/content - streams progress to the Messages tab with RAISERROR ... WITH NOWAIT 5. Returns result data - prints the answer in chunks - returns one result set with status, run info, elapsed time, steps, cost, and tools used


Inputs

@q

The question to ask the assistant.- Required in practice- Blank or whitespace-only input raises an error and returns immediately

@thread

Conversation thread to continue. If omitted, it defaults to: sql ssms:<user>

That is deliberate: test traffic stays out of the application user’s chat thread unless explicitly routed there.

@new

If 1, archives prior turns in the current thread before starting a fresh conversation. This does not delete anything. It sets archived = 1 on existing dbo.agent_chat rows for the thread.

@wait_s

Maximum time to wait for a reply, in seconds. Default: 300

@card

Optional card name for context. The procedure looks up dbo.api_card.name = @card and passes the corresponding card_id into sp_openai_chat_post.

@record_id

Optional record context passed through to the chat post.

@quiet

If 1, suppresses progress narration and answer printing. Useful for scripting.

@throw

If 1 (default), the procedure raises on timeout or failure. If 0, it returns status information in the result set instead.

@user_name

Override for the asking identity. If omitted, uses SUSER_SNAME(). This matters because the assistant’s cross-conversation scoping keys off the user name.


Outputs

OUTPUT parameters

  • @answer — the assistant response text
  • @chat_id — the chat row / reply identifier

Result set

One final result set is returned with: - chat_id - run_id - status - run_status - elapsed_s - steps - usd - tools - thread_id - answer


Environment checks

The procedure is defensive before it queues anything.

1) Empty question check

If @q is null or whitespace: - raises an error - returns 1

2) Explicit transaction check

If @@TRANCOUNT > 0: - raises an error - returns 1

Reason: SEND ON CONVERSATION is transactional, so the worker would not activate until commit. Waiting inside a transaction would deadlock the caller in a very patient way.

3) Service Broker enabled

It checks the current database: sql SELECT 1 FROM sys.databases WHERE database_id = DB_ID() AND is_broker_enabled = 1

If not enabled: - raises an error - returns 1

4) Queue existence and activation

It inspects: - sys.service_queues.is_receive_enabled - sys.service_queues.is_activation_enabled - sys.service_queues.activation_procedure

for queue openai_chat_queue. It distinguishes three separate failure modes: - queue missing - queue receive disabled - queue exists but activation disabled

Each gets its own error message.

5) API key precheck

It tries to read: sql EXEC dbo.sp_api_setting_get @key = N'openaiApiKey', @value = @api_key OUT

If the caller lacks permission, it treats that as “cannot verify” and continues. If the key is verifiably empty, it aborts. That’s a nice little example of the procedure preferring a false negative over a false certainty. Rare, and good.


Thread handling

If @thread is empty, the procedure generates: sql ssms:<user>

Where <user> comes from @user_name or SUSER_SNAME(). This avoids polluting the app’s normal user thread.

If @new = 1, it archives prior turns in that thread first: sql UPDATE dbo.agent_chat SET archived = 1 WHERE thread_id = @thread AND archived = 0

Then it logs how many turns were archived.


Card context resolution

If @card is supplied: - it looks up dbo.api_card.id by name - takes the first matching row ordered by id - passes that card_id to sp_openai_chat_post

If no card is found, it raises an error and stops.


Core ask path

The actual request is posted by: sql EXEC dbo.sp_openai_chat_post @thread_id = @thread, @message = @q, @user_name = @user, @card_id = @card_id, @record_id = @record_id, @reply_id = @chat_id OUTPUT

That is the only place where the question is submitted. sp_ask_ai itself does not generate the answer. It waits for the already-existing agent pipeline to do that.


Polling and progress reporting

After posting, the procedure polls dbo.agent_chat for the chat_id it just got back.

Poll loop

  • sleeps 1 second per iteration
  • stops when status is no longer pending
  • stops when @wait_s is reached

Progress narration

If @quiet = 0, it prints progress with: - RAISERROR(..., 10, 1) WITH NOWAIT

This is intentional: - severity 10 means message, not error - WITH NOWAIT flushes immediately to the client

It also reads recent rows from dbo.api_grok_agent_steps for the current run_id and prints the tool calls as they happen. That makes the procedure useful as a live diagnostic window, not just a “submit and hope” wrapper.


Answer output behavior

If the conversation finishes with status = 'done' and @answer is not null: - the answer is printed in chunks - chunking avoids the 4,000-character truncation issue of plain PRINT

The implementation tries to cut on a newline boundary when possible so code blocks survive better.


Cost and usage reporting

After completion, it looks up: - step count and spend from dbo.vw_ask_ai_spend_turn - distinct tool names from dbo.api_grok_agent_steps

It then prints a summary like: - status - elapsed seconds - step count - USD cost - chat id


Return codes

The procedure uses return codes as follows: - 0 — success, answer delivered and run completed normally - 1 — local validation / environment failure - 2 — still pending after @wait_s - 3 — run ended with non-done status - 4 — answer was delivered, but the underlying run ended in a non-done state

That last one is an important nuance: the chat row may contain an answer even when the run status says it did not finish cleanly.


Error handling philosophy

This procedure is opinionated in a useful way: - it distinguishes “cannot verify” from “absent” - it checks the boring details early. - it does not silently hang on broker/queue problems - it prints what the agent is doing while it is doing it - it preserves the answer even when the run status is imperfect

It is built for operator clarity, not for elegant minimalism.

Notable implementation details

  • 1) It does not duplicate the agent

The procedure uses the same downstream chat worker path as the App. It is not a second AI implementation.

  • 2) It reads both dbo.agent_chat and dbo.api_grok_agent_runs

This is deliberate:

  • agent_chat holds the chat row and content
  • api_grok_agent_runs holds the run status
  • the two can differ, and the difference matters

  • 3) It uses run_id for progress, not timestamp

That avoids mixing up another user’s newer run in a multi-user environment.

  • 4) It avoids PRINT truncation

Long answers are chunked manually.

  • 5) It treats partial success as a distinct state

A reply may exist even if the run did not end done.

Practical usage example

``` DECLARE @answer nvarchar(max), @chat_id int;

EXEC dbo.sp_ask_ai @q = N'Create a technical description of procedure sp_ask_ai', @quiet = 0, @answer = @answer OUTPUT, @chat_id = @chat_id OUTPUT;

SELECT @chat_id AS chat_id, @answer AS answer; ```

Summary

dbo.sp_ask_ai is a synchronous operator-facing wrapper around the asynchronous AI chat pipeline. Its job is not to invent answers; it is to make the existing chat system usable from T-SQL while surfacing the failure modes that would otherwise look like a hang.

If you want, I can also turn this into a more formal artifact style, for example:

  • a module reference page
  • a code walkthrough
  • a sequence diagram
  • or a “what it touches” dependency note

r/SQLServer 9d ago

Question SQL Server 2019 Standard >SQL Server 2025 Standard Developer

2 Upvotes

Is it possible to upgrade from the SQL Server 2019 Standard (non-developer) to the SQL Server 2025 Standard Developer edition?


r/SQLServer 10d ago

Question SQL Server on SSD

0 Upvotes

Hey guys, I started a local WoW server just for myself using SQL on an SSD. I saw some information that it could kill my SSD faster. Should I be worried? Or can I just play without worrying?


r/SQLServer 11d ago

Certification Passed DP-800 today (SQL AI Developer Associate)

Post image
10 Upvotes