'Get Parameters of sqlcommand to string
I'm creating an error log for a webpage. I need a way to get the parameters from a SQL Command to output to string so that the parameters passed through keep the query as dynamic as possible for use throughout the site.
Heres the SQL Command Type I'm talking about:
SqlCommand cmdErrReport = new SqlCommand("ERROR_LOG", conn.sbConn);
cmdErrReport.CommandType = CommandType.StoredProcedure;
cmdMarineResort.Parameters.Add("@Statement", SqlDbType.VarChar).Value = "FindSeason";
I was trying something like this:
cmdMarineResort.Parameters.ToString()
but I can't find within the .Parameters query how to find parameter names or values.
How would I be able to get the values to string? Would i have to list the parameters and the loop through that list writing the parameter and its value to string? If so, how?
Solution 1:[1]
cmdMarineResort.Parameters
is a SqlParameterCollection.
You can iterate through it using a foreach
statement:
foreach(SqlParameter Para in cmdMarineResort.Parameters)
{
Console.WriteLine((string)Para.Value); //value of the parameter as an object
}
Solution 2:[2]
This worked for me Using MSSQL Server:
private static string getQueryFromCommand(SqlCommand cmd)
{
string CommandTxt = cmd.CommandText;
foreach (SqlParameter parms in cmd.Parameters)
{
string val = String.Empty;
CommandTxt+=parms.ParameterName + "=";
if ((parms.Value == null)) // string.IsNullOrEmpty(parms.Value))
{
CommandTxt+="NULL, ";
}
else
{
CommandTxt+=(string)parms.Value.ToString() + ", ";
}
}
return (CommandTxt);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Thirisangu Ramanathan |
Solution 2 | Craig Jones |