简体   繁体   中英

Is it possible to automatically get a list of parameters defined in a query string using SqlClient

I am working on a C# project that takes parameterized queries and saves them - then executes them on a schedule and emails out results (if any records are returned).

I am using the System.Data.SqlClient namespace to create SqlConnection , SqlCommand to contain the query and parameter information, and SqlDataReader to get the results of the query from the SqlCommand into something I can work with.

I have routines in place that "crawl" the supplied query to find any parameters in the string text (looking for words that start with "@") and save those as well - and it works fine - but I was wondering if there is something in the SqlClient library that will take the query text and output a list of found parameters?

After researching the question, I haven't come up with anything that says you can get a list of parameters defined in the query text by using "this thing".

It may not be possible, and this is simply me wondering if it is. Currently, after getting a list of parameters by crawling the query string, I have to ask the user to define the datatypes - and that could go away if it's possible to get a list automatically.

If you do not add a parameter to the SqlCommand that exists in the query string - you will get an exception saying something like

@ParameterName is defined in the query but no value was given

which is what makes me think it may be possible.

Not in SqlClient, as it has no data type information about the parameters. But SQL Server can infer parameter types from the column comparison expressions they are used in.

So check out the system stored procedure sp_describe_undeclared_parameters to give you this information.

By executing this query, you can find the list of parameters of SP

SELECT
param.parameter_id AS [ID],
param.name AS [Name]
FROM
sys.all_objects AS sp
INNER JOIN sys.all_parameters AS param ON param.object_id=sp.object_id
WHERE
(sp.type = 'P' OR sp.type = 'RF' OR sp.type='PC')and(sp.name='SP_NAME' and SCHEMA_NAME(sp.schema_id)='dbo')
ORDER BY
[ID] ASC

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