简体   繁体   中英

Obtaining stored procedure parameter dynamically by name

Let's create a stored procedure with many similar input parameters with the same type:

CREATE PROCEDURE [dbo].[SampleStoredProcedure]
    @p1 NVARCHAR(MAX) = NULL,
    @p2 NVARCHAR(MAX) = NULL,
    @p3 NVARCHAR(MAX) = NULL,
    ...
    @p1000 NVARCHAR(MAX) = NULL

At the beginning, inside the procedure, I want to generate a list of parameters (strings) I should to use, which depends on some database data.

For example, I have 1000 parameters, but I want to read only 10, and execute some SQL statement with these values.

  1. Is it possible to get the parameter by its name as string? Any dynamic SQL query?

  2. Maybe there is some way to iterate through all input parameters and check if the list contains the current one?

It is possible to generate the SQL with some condition for each parameter separately but the stored procedure will be very long and difficult to modify later. Probably the performance will be worse than in 1. method too. Table Valued Parameter is a solution too, but the point is to avoid it, using separated parameters.

Summary: I have a list of strings defining which input parameters should be mapped and I just want to ignore others, to avoid additional conditions. The SQL query should be executed only with some input parameters - defined by a context in other table.

Some example:

-- It will generate parameters' list - some context.
DECLARE MyCursor CURSOR
    LOCAL STATIC READ_ONLY FORWARD_ONLY
FOR
    SELECT [FieldName] FROM [Fields] AS [F] WHERE [F].[ProjectId] = @ProjectId

-- It will execute some action only for defined input parameters.
OPEN MyCursor
FETCH NEXT FROM MyCursor INTO @FieldName
WHILE @@FETCH_STATUS = 0
BEGIN 
    -- It doesn't work, but it illustrates the problem.
    SET @FieldValue = N'@' + @FieldName
    EXEC sp_executesql @Query, @Params, @FieldName = @FieldName, @FieldValue = @FieldValue
    FETCH NEXT FROM MyCursor INTO @Field
END
CLOSE MyCursor
DEALLOCATE MyCursor

This will return the name of all parameters for a given Stored Procedure

 SELECT
    p.name
    ,p.max_length
FROM
    sys.all_objects o
JOIN
    sys.all_parameters p
ON
    o.object_id = p.object_id
WHERE
    o.name = 'myStoredProcedure'  -- name of stored procedure

If we assume that your parameters(not TVP) have known names(this can be done dynamically using DMVs and Dynamic-SQL), you can use some workaround like:

1) Create Linked Server to itself

2) Query itself using OPENQUERY

Your:

-- It doesn't work, but it illustrates the problem.
SET @FieldValue = N'@' + @FieldName

Will be:

SELECT @FieldValue = 
    (SELECT * FROM OPENQUERY('loopback_servername','SELECT ' + @FieldName))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM