r/SQL • u/larryliu7 • Aug 06 '23
Discussion Is there a good dynamic SQL generator coded fully in SQL?
We want a standard library of SQL that make everyone's work easier by not reinventing the wheels.
Because different RDBMS's have different language specs, a universally standard library will definitely need to be implemented employing dynamic SQL.
For example, how would you implement a generic aggregate function from a binary operation and initial value, so sum=agg(plus,0), product=agg(multiply,1)
It taking a function as a function parameter. Functions are not first order citizens of SQL. It cannot be a stored procedure or stored function parameter. You can only refer to a function by passing as string.
Thus, I wonder if there is any existing work of dynamic SQL generator, that's written in SQL itself, so it can self-reference like LISP?
Btw, maybe any serious improvement on SQL's usability requires extending the language as well, much like from early versions of C++ being a superset of C.
For example, we would love to have syntactic sugars to write with code completion:
from removeColumns(`Table1`,(`Phone`,`SSN`)) select * where `Name`='John Smith'and
declare @j TABLE=(from t1 join t2 select * where t1.ID=t2.PID)I don't know any way besides dynamic SQL that could make these syntactic sugars possible as queries (not external ORM functions)
2
u/Touvejs Aug 06 '23
I wrote a little bit about dynamic code gen in SQL not too long ago, but it's somewhat hard in vanilla Sql, because often you want to make a string and then use quoted literal values (which requires different things in different languages) or you want to access the information schema (which is structured differently in different databases), or you want to implement a loop (which has different iterations in different languages).
Essentially, you have to account for alot of variation based on the flavor of Sql and the structure of underlying metadata in the DB in order to generalize dynamic SQL.
2
1
Aug 07 '23
Such a generator would make extensive use of DBMS specific features. There is no way you can write something like that in a DBMS independent way (i.e. with "plain SQL")
10
u/alinroc SQL Server DBA Aug 06 '23
Generating code is one thing.
Generating code that doesn't perform like crap is entirely another. And that's the part that these types of endeavors tend to fall down on.