Parameterized Dynamic TSQL - Dynamic Parameters

by Kirk Saunders   Last Updated July 12, 2019 14:06 PM

Lets assume I build out a Dynamic SQL Command where the output looks something like:

SELECT
Col1 AS 'Alias1',
Col2 AS 'Alias2',
Col3 AS 'Alias3'
FROM View
WHERE DateCol >= @StartDate
AND DateCol < @EndDate

To execute this command (assuming the command text is stored in a variable called @SqlCommand we would use code like:

EXECUTE sp_executesql @sqlCommand 
N'@StartDate DATETIME, @EndDate DATETIME', 
@StartDate = '2019-01-01', 
@EndDate = GETDATE()

Is there a way to dynamical change the parameters that are configured and passed in without having to build a separate command?

I know I can make declaring the parameters a variable and build that dynamical if I need to.

DECLARE @Parameters = '@StartDate DATETIME, @EndDate DATETIME'

I don't know however how to dynamically generate the process of providing the parameters their values. How to dynamically handle the piece after declaring the parameters (since they are not passed in as just a string literal.

, 
@StartDate = '2019-01-01', 
@EndDate = GETDATE()


Related Questions





Passing array from one plpgsql function to another

Updated August 24, 2015 18:02 PM