Skip to content

Dynamic SQL Logging, String Functions, SQL Debug Example: small correctness fixes - #957

Merged
erikdarlingdata merged 2 commits into
devfrom
fix/admin-small-tsql
Nov 13, 2026
Merged

erikdarlingdata merged 2 commits into
devfrom
fix/admin-small-tsql

Conversation

@erikdarlingdata

Copy link
Copy Markdown
Owner

Dynamic SQL Logging: physical reads went negative

What went wrong. dbo.logging computed physical reads as reads - logical_reads. In sys.dm_exec_requests, reads is already the physical read count, so on a warm cache (logical greater than physical) the logged physical_reads_mb was negative, in both the first pass and the second pass.

Fix. Both passes now use r.reads (the second pass had an unqualified reads - logical_reads that bound to r). The variables @cpu_time, @total_elapsed_time, @reads, @writes and @logical_reads were declared and never used, so they are removed.

Proof (SQL2019, scratch db). A batch scans a 20000-row table 5 times (warm cache), calls dbo.logging with @guid_in = NULL, scans 5 more times, then calls it again with the first run hash.

pass 1 physical MB pass 1 logical MB pass 2 physical MB pass 2 logical MB
before -129.42 129.48 -114.17 114.16
after 0.00 113.68 0.00 113.90

String Functions: strip_characters dropped trailing spaces

What went wrong. Both variants sized their number list with TOP (LEN(...)). LEN ignores trailing spaces, so trailing spaces in the input were never visited and never returned. strip_characters_cte(N'ab12 ', N'0-9') returned ab, not ab plus two spaces. An all-space input returned NULL.

Fix. Both variants now use TOP (DATALENGTH(ISNULL(@string, N'')) / 2). The parameter is nvarchar(4000), so the character count is bytes divided by 2. get_letters and get_numbers have the same LEN pattern but cannot keep a space, so their output does not change and they are untouched.

Proof (SQL2019, scratch db with a Numbers table). Result length in bytes:

input pattern before (both variants) after (both variants)
ab12 + 2 spaces 0-9 4 bytes, [ab] 8 bytes, [ab ]
2 spaces + a b1 + 2 spaces 0-9 10 bytes, [ a b] 14 bytes, [ a b ]
3 spaces (cte) 0-9 NULL 6 bytes, [ ]

Empty string and NULL input still return NULL.

README. String Functions/README.md now says that edge spaces stay in the result, and documents error 6841. The functions build the result with FOR XML, so kept text with a control character other than tab, CR or LF fails with 6841 (reproduced with NCHAR(1); tab, CR and LF pass). There is no SQL Server 2016-safe code fix, so this is documentation only. The README also gives the workaround, tested on both variants: add the character to the match expression (N'0-9' + NCHAR(1) returns ab). The plain-english checker reports no hits on the lines I added.

SQL Debug Example: print loop repeated characters, default run failed

(a) Print loop. The loop printed @block_size characters per block but advanced @block_size - 1, so every block repeated the last character of the previous block. It now advances @block_size. I also fixed the comment below the loop: @block starts at 1, not zero.

Proof: I ran the real procedure @debug_logic = 1, @execute_sql = 0 through pyodbc and summed the PRINT blocks (41 blocks both times):

string length characters printed
before 8011 8051 (40 repeated)
after 8013 8013

A scratch copy of the loop agrees: the rebuilt text equals the string only after the fix.

(b) Default run. @execute_sql defaults to true, but the faked long dynamic SQL was SELECT x = followed by a bare AAAA...BBBB identifier, so EXECUTE dbo.DebugExample; failed with Msg 103 (identifier too long). The string is now SELECT x = ' + 8000 characters + ', a quoted string literal that is still about 8000 characters long, so the print loop still has a long string to print.

Proof: EXECUTE dbo.DebugExample; on SQL2019. Before: Msg 103, "The identifier that starts with 'AAAA...' is too long". After: runs to the end, zero errors, returns the 8000-character value.

Dropped

Nothing. All three findings still held at b7fba0f.

Test notes

  • go-sqlcmd stalls on the PRINT loop under @debug_logic = 1; the server finishes (no lingering request), the client does not. The file also ends with a demo EXEC ... @debug_logic = 1, @debug_performance = 1 that I kept out of my install step. The pyodbc capture above avoids the stall.
  • Scratch database zz_fix_c_1 on SQL2019 is dropped.

Considered, not added

  • Making the strip functions survive control characters (error 6841): no SQL Server 2016-safe form exists without leaving FOR XML, so it is documented.
  • Changing get_letters and get_numbers to DATALENGTH: no behavior change (a space is never kept), so no concrete trigger.
  • Surrogate pairs in the strip functions: SUBSTRING under the BIN2 collation walks UTF-16 code units, and DATALENGTH / 2 counts the same units, so it is consistent.

🤖 Generated with Claude Code

https://claude.ai/code/session_01M98owc3zzZNEpij3p49Bbe

…ctness fixes

- Dynamic SQL Logging: log physical reads from r.reads (already physical) in both passes instead of reads - logical_reads, which went negative on a warm cache; drop unused variables.
- String Functions: strip_characters and strip_characters_cte count characters with DATALENGTH / 2 so trailing spaces are kept; README documents the kept-space behavior and error 6841 for control characters.
- SQL Debug Example: print loop advances @block_size so blocks no longer repeat a character; the faked long dynamic SQL is a quoted string literal so the default run executes.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01M98owc3zzZNEpij3p49Bbe
@erikdarlingdata
erikdarlingdata marked this pull request as ready for review November 13, 2026 08:44
@claude

claude Bot commented Nov 13, 2026 •

Copy link
Copy Markdown

Claude finished @erikdarlingdata's task in 12s —— View job


Review

No blocking issues found. The changes look correct and match the PR description. I read the diff only and did not run any of it.

  • Dynamic SQL Logging: r.reads is already the physical read count, so dropping - r.logical_reads is right. The second pass is now qualified with r.. The removed variables are unused.
  • strip_characters: DATALENGTH(...) / 2 is correct for nvarchar(4000). DATALENGTH returns bytes and an nvarchar character is 2 bytes, so the count is exact. The /* */ comments follow the style guide. There is no version-compatibility concern, since both functions work on SQL Server 2016.
  • DebugExample: advancing by @block_size fixes the repeated character, because SUBSTRING is 1-based and @block starts at 1. The quoted literal now makes the default run valid. Two small things:
    • The @block comment now says 1, which is correct.
    • The new nvarchar(MAX) casing on the existing line is not part of this PR. It breaks the lowercase rule in CLAUDE.md, but it is optional to fix here.
  • README: the notes on edge spaces and error 6841 are clear.
  • Repo rules: no @version or @version_date bumps, and Install-All/DarlingData.sql is not touched.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01M98owc3zzZNEpij3p49Bbe
@claude

claude Bot commented Nov 13, 2026 •

Copy link
Copy Markdown

Claude finished @erikdarlingdata's task in 11s —— View job


Review (updated for latest push)

No blocking issues found. I read the diff only and did not run any of it.

  • Dynamic SQL Logging: r.reads is already the physical read count, so dropping - r.logical_reads is correct in both passes. The second pass is now qualified with r.. The removed variables were unused.
  • strip_characters: DATALENGTH(...) / 2 gives the exact character count for nvarchar(4000), so trailing spaces are now kept. It works on SQL Server 2016, and the comments use /* */.
  • DebugExample:
    • Advancing by @block_size fixes the repeated character.
    • The quoted literal makes the default run valid.
    • The new commit lowercases nvarchar(max), which resolves the style nit from the earlier review.
  • README: the notes on edge spaces and error 6841 are accurate and clear.
  • Repo rules: no @version or @version_date bumps, and Install-All/DarlingData.sql is not touched. No new object dependencies.

@erikdarlingdata
erikdarlingdata merged commit 59f6a82 into dev Nov 13, 2026
7 checks passed
@erikdarlingdata
erikdarlingdata deleted the fix/admin-small-tsql branch November 13, 2026 08:47
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant