I have a stored procedure, that inserts some data into a table. At the end, I want to UPDATE STATISTICS on that table. The user which is executing the procedure, does not have sufficient permissions to run UPDATE STATITICS. Now, my idea was to create a stored procedure, which is executes as owner (has sufficient permissions) and grant the user execute permission on this stored procedure. So far it works, but if I execute the procedure with
EXEC dwh.sp_UpdateStatistics @schemaName = 'dwh', @tableName = 'dim_Assets;SELECT 123;'
it returns 123.
I have read about SQL injection, but I could not figure out how to solve this issue.
This is the procedure:
CREATE PROCEDURE dwh.sp_UpdateStatistics @schemaName VARCHAR(10) = NULL, @tableName VARCHAR(50) = NULL
WITH EXECUTE AS owner
AS
DECLARE @updateStatistics NVARCHAR(MAX);
SET @updateStatistics = N'UPDATE STATISTICS ' + @schemaName + '.' + @tableName;
EXEC sp_executesql @updateStatistics;
Could you please help me out to find a way how to update the statistics without granting any more permissions and without having the risk of SQL injections. (It is not that they are expected, it is fully inhouse, but it is simply for the sake of having a good sleep and the feeling of "doing it the correct way") Thank you! (I have SQLServer2017 but I cannot create a post with this tag.)