SQL Server front-end (T-SQL)

Stage 7 (server cursors, FORMAT, grouping sets, 2022 functions)

Server cursors for JDBC, ODBC and ADO, keyset and dynamic T-SQL cursors, LIKE / PATINDEX / FORMAT with any expression, GROUPING SETS, the newer T-SQL functions, PARSE with cultures, CONTAINS conditions.

Built for the real client libraries: the server cursor protocol works with the Microsoft JDBC driver, the ODBC Driver 17 and the OLE DB Driver for SQL Server, and FORMAT follows the .NET formats.

Server cursors (srvcursor.rs, raftdb-tds). sp_cursoropen, sp_cursorfetch, sp_cursor, sp_cursoroption, sp_cursorclose, sp_cursorprepare, sp_cursorexecute, sp_cursorprepexec, sp_cursorunprepare, as RPCs (the well-known ids 1 to 9 or the names, with positional or named parameters) and as EXEC sp_cursoropen @h OUTPUT, N'...' in a batch. This is what the drivers send for a scrollable or updatable result set: JDBC TYPE_SCROLL_INSENSITIVE / TYPE_SCROLL_SENSITIVE / TYPE_SS_SCROLL_DYNAMIC / TYPE_SS_SERVER_CURSOR_FORWARD_ONLY, CONCUR_UPDATABLE (updateRow, deleteRow, insertRow, refreshRow, rowDeleted), selectMethod=cursor; ODBC and ADO server-side cursors (adOpenKeyset, adOpenStatic, adLockOptimistic: MoveLast, Move, AbsolutePosition, Update, Delete, AddNew, RecordCount).

  • @scrollopt: KEYSET 1, DYNAMIC 2, FORWARD_ONLY 4, STATIC 8, FAST_FORWARD 16, with PARAMETERIZED_STMT 0x1000 (the declaration and the values follow), AUTO_FETCH 0x2000 (the open returns the first rows), AUTO_CLOSE 0x4000. @ccopt: READ_ONLY 1, SCROLL_LOCKS 2, OPTIMISTIC 4 and 8, with ALLOW_DIRECT 0x2000. What is served comes back in @scrollopt (as SQL Server does when it converts a cursor): a dynamic cursor is served as a keyset cursor (1) on a table with a primary key and as a static one (8) otherwise; a keyset cursor on a query that is not one table with a primary key is static (8). @rowcount is the number of rows (-1 for a forward-only cursor without AUTO_FETCH).
  • sp_cursorfetch: FIRST 1, NEXT 2, PREV 4, LAST 8, ABSOLUTE 0x10 (negative: from the end), RELATIVE 0x20, REFRESH 0x80, INFO 0x100 (position and row count in @rownum and @nrows), PREV_NOADJUST 0x200; blocks of @nrows rows; FIRST / LAST with 0 rows put the cursor before the first / after the last row. Every row has one more column at the end, ROWSTAT (1: fetched, 2: the row is missing).
  • sp_cursor: UPDATE 1, DELETE 2, INSERT 4, REFRESH 8, LOCK 16, with SETPOSITION 32 and ABSOLUTE 64; @rownum counts in the fetch buffer (0: every row of it); the values are parameters named after their columns, or one text ([UPDATE t] [SET] a = 1, ..., [INSERT [INTO] t] [(cols)] VALUES (...)). The row is found by the primary key (a cursor without one: by all selected columns). A row inserted through a keyset cursor becomes its last row (when its key is among the named values, or is the identity value); sp_cursoroption @h, 2, N'name' names the cursor for WHERE CURRENT OF name.
  • A statement that is not a query: when it gives exactly one result set (EXEC proc), the cursor is over those rows (static, read only); otherwise it runs directly when ALLOW_DIRECT is set (the handle is 0) and is error 16937 without it.
  • On the wire (raftdb-tds): the fetch buffer is Item::Cursor; after COLMETADATA come TABNAME and COLINFO (the JDBC driver refuses to update a column that has no table there; the ODBC driver hides ROWSTAT because COLINFO says it is hidden); the columns of an updatable cursor are announced read/write; an RPC with fNoMetaData (the OLE DB driver sets it on sp_cursorfetch) gets COLMETADATA with 0xFFFF columns and the rows in the layout of the open (the OLE DB driver crashed on anything else); outputs without a name go back at the position of their own parameter. LOGINACK now names the program Microsoft SQL Server (the OLE DB driver refused to connect to anything else).
  • Errors: 16909 (unknown handle), 16911 (a fetch type on a forward-only cursor), 16929 (read only), 16930 (the row is not in the fetch buffer), 16934 (no row was changed), 16937, 8179 (unknown prepared handle).

T-SQL cursors (cursor.rs). The models: STATIC / INSENSITIVE (the rows of OPEN); KEYSET (membership and order of OPEN, each FETCH reads the row again by its primary key: other columns show their current values, a deleted row is @@FETCH_STATUS = -2); DYNAMIC, FAST_FORWARD and a cursor declared without a model (like keyset, but a deleted row is skipped). A query that is not one table with a primary key (a join, an aggregate, DISTINCT, TOP, a view, a table without a key) is static whatever was declared. FORWARD_ONLY is the default unless SCROLL or a model is written: another fetch type is error 16911; FETCH ABSOLUTE on a cursor declared DYNAMIC is error 16911. WHERE CURRENT OF finds the row by the primary key (so the cursor need not select all columns, and an updated row can be updated again); a READ_ONLY / FAST_FORWARD cursor is error 16929. Also: the ISO form DECLARE c [INSENSITIVE] [SCROLL] CURSOR FOR, @@CURSOR_ROWS (-1 for a dynamic cursor), CURSOR_STATUS('global' | 'local' | 'variable', 'name'), DECLARE @a CURSOR, @b CURSOR, SET @c = cursor_name / SET @c = @d (the variable refers to that cursor; DEALLOCATE @c lets go of it), sp_describe_cursor, error 16924 for a wrong number of INTO variables.

LIKE, PATINDEX, FORMAT (engine functions __TSQL_LIKE, __TSQL_PATINDEX, __TSQL_FORMAT in raftdb-mysql, tsqlfn.rs). LIKE with a pattern that is a column, a variable, a parameter or an expression reads %, _, [a-z], [^0-9] as T-SQL does (before: such a pattern went to the engine's LIKE, where a class was ordinary text), and ESCAPE takes any expression. PATINDEX takes any pattern (wildcards and classes anywhere) and any expression. FORMAT(value, format [, culture]): every .NET standard format (N, F, C, P, E, G, D, X, R with a precision; d D t T f F g G M Y s u O R for dates) and custom format (0 # . , %, sections pos;neg;zero, quoted text, \x; yyyy MM MMM MMMM dd ddd dddd HH hh mm ss fff tt zzz ...), with the format and the culture as any expression, in fifteen cultures (en-US, en-GB, de-DE, fr-FR, es-ES, it-IT, pt-BR, nl-NL, ja-JP, ru-RU, sv-SE, pl-PL, en-IN, en-AU, en-CA: their data was written out from .NET's CultureInfo). A text value is error 8116; a literal culture outside the list is refused (40000), one that is not a literal gives NULL; FORMAT of a time is refused (its formats are TimeSpan's).

Queries. GROUP BY GROUPING SETS ((a, b), a, ()), ROLLUP(a, b), CUBE(a, b), GROUP BY (), GROUP BY a, b WITH ROLLUP | WITH CUBE, mixed with plain columns, with GROUPING(x) and GROUPING_ID(x, y): one grouped query for each grouping set, joined by UNION ALL (TOP, DISTINCT and INTO with them are refused; ORDER BY takes output columns or positions). a IS [NOT] DISTINCT FROM b. PIVOT over a derived table with its grouping column in the select list (was error 207). PERCENT_RANK(), CUME_DIST(), PERCENTILE_CONT(p) WITHIN GROUP (ORDER BY x) OVER (...), PERCENTILE_DISC, CHECKSUM_AGG (the XOR of the values, as SQL Server computes it).

Functions. JSON_OBJECT('k': v, ... [NULL ON NULL | ABSENT ON NULL]), JSON_ARRAY(v, ... [NULL ON NULL | ABSENT ON NULL]), JSON_PATH_EXISTS, BIT_COUNT, LEFT_SHIFT, RIGHT_SHIFT, GET_BIT, SET_BIT, LTRIM(text, characters), RTRIM(text, characters), STRING_ESCAPE(text, 'json'), TIMEFROMPARTS, DATETIME2FROMPARTS, DATETIMEFROMPARTS, SMALLDATETIMEFROMPARTS, XACT_STATE(), FORMATMESSAGE('text %s %d', ...) (a literal format), DATEDIFF / DATEDIFF_BIG(nanosecond, ...). CONVERT date to text: styles 9 / 109, 13 / 113, 14 / 114, 127, and the fraction of styles 21 / 121 / 126 is the value's (it was always .000: the engine's DATE_FORMAT has no %f); money to text: styles 0, 1 (commas), 2 (four decimals); text to date: styles 2 / 102, 6 / 106, 7 / 107, 9 / 109, 13 / 113. PARSE(text AS type USING 'culture') and TRY_PARSE: numbers with the culture's group and decimal separators and currency sign, dates in the culture's order of day, month and year (or ISO) with an optional time. TRY_CAST / TRY_CONVERT to tinyint, smallint, int: a value outside the type's range is NULL.

Full-text. A CONTAINS condition may mix AND, OR and AND NOT (with AND before OR) and use parentheses; a NEAR b, a ~ b, NEAR(a, b), NEAR((a, b), MAX) find the rows that have all the terms and ISABOUT(a WEIGHT(0.8), b) those that have any (distance and weights only change SQL Server's rank, which is not built); CONTAINS((a, b), '...') and FREETEXT((a, b), '...') match when one of the columns does. Groups are put together with SQL's AND / OR / NOT over one MATCH each (the engine's boolean mode has no groups).

Clients. Cursors and the new functions work in process and through sqlcmd; mssql-jdbc 13.6.2 (scrollable and updatable result sets and selectMethod=cursor), System.Data.SqlClient (the sp_cursor* procedures with named and output parameters) and ADO Recordset server-side cursors (through the OLE DB Driver for SQL Server and through the ODBC Driver 17) work too.

Differences and limits of this stage. A dynamic cursor does not see rows inserted after OPEN (SQL Server's does) and keeps the order of OPEN; a keyset cursor finds a row whose key was changed elsewhere as missing, as SQL Server does, but a row inserted through sp_cursor with a text value is not added to it; a cursor declared in a procedure still ends with the procedure; optimistic concurrency is not checked (an update through a cursor of a row another session changed in between goes through); sp_cursorfetch always answers status 0; cursor handles start at 180150003 like SQL Server's but are the session's own; the text of error 16911 for sp_cursorfetch may differ from SQL Server's. PARSE of text that cannot be read gives NULL (SQL Server: error 9819) and reads no month names; DATETIMEFROMPARTS and its relatives give NULL for parts that are not valid (SQL Server: error 289); LEFT_SHIFT and the other bit functions follow the engine's 64-bit arithmetic for negative numbers; FORMAT of a float uses the shortest text of the number (the .NET Framework rounds to 15 digits first), STRING_ESCAPE escapes the characters that have a short form (not the other control characters as \u00XX); GROUPING SETS over an empty table gives the grand total row of () also for ROLLUP and CUBE.

Still refused or missing after this stage (40000 or SQL Server's own error): hierarchyid; FORMSOF and NEAR with a distance or an order in CONTAINS; AT TIME ZONE, SWITCHOFFSET, TODATETIMEOFFSET, DATE_BUCKET; the WINDOW clause; IGNORE NULLS / RESPECT NULLS; the << and >> operators (the functions LEFT_SHIFT / RIGHT_SHIFT work); NEXT VALUE FOR ... OVER; HASHBYTES('SHA2_512'); COMPRESS / DECOMPRESS; NEWSEQUENTIALID; TYPEPROPERTY; CONVERT styles 22, 130, 131; FORMAT of a time; MERGE TOP; ALTER TABLE ... ADD of an identity column; filtered indexes other than a unique one WHERE col IS NOT NULL; STBuffer, BufferWithTolerance, Reduce, MakeValid; a cancel under MARS and rows of two MARS replies interleaved; Agent retries and alerts; differential, log and file backups.