Pass table, column and order by clauses as SQL variables

In general, in standard SQL, we cannot pass table or column name as a variable, so this would be impossible:

SET @TableName = 'MyTable';
SET @Offset = 0;
SET @Limit = 10;
SELECT * FROM @TableName LIMIT @Offset,@Limit

However, there is a workaround with custom SQL extensions for various databases. E.g. in MariaDB, it would be like this:


SET SQL = CONCAT('SELECT * FROM ', @TableName, ' LIMIT ?,?');
PREPARE stmt FROM @SQL;
EXECUTE stmt USING @Offset,@Limit;
DEALLOCATE PREPARE stmt;

As we can see from that example we can pass parameters to the statement we generate, but again, it does not include table or column names, so we concatenate the table or columna as a variable. It is very helpful to pass it like this since many DB ORM frameworks sanitize the parameters and we ensure there are no SQL injections. Of course passing a table or column name as a parameter is very dangerous and we should manually ensure that these names are allowed for use

In MSSQL we should use sp_prepare which does essentially the same: https://learn.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sp-prepare-transact-sql?view=sql-server-ver16

Post a Comment

Previous Post Next Post