I have a sql query like this:
UPDATE StockUpdateQueue SET Synced = 1, SyncedAt = GETDATE() WHERE Id IN (@p0,@p1);
This query is dynamically generated. What I want to do is run it through a function, which will effectively replace all the @pN parameters with their corresponding values.
I have tried to do this with standard string.Replace as well as Regex.Replace with no luck - the replace is not taking place.
This is what I tried so far:
class Program
{
static string _lastQuery;
static void Main(string[] args)
{
var sqlQuery = "UPDATE StockUpdateQueue SET Synced = 1, SyncedAt = GETDATE() WHERE Id IN (@p0,@p1);";
var sqlParamters = new Dictionary<string, object>()
{
{ "@p0", 12345 },
{ "@p1", 65432 }
};
LogLastQuery(sqlQuery, sqlParamters);
}
static void LogLastQuery(string sqlQuery, Dictionary<string, object> sqlParamters = null)
{
_lastQuery = sqlQuery;
if (sqlParamters != null && sqlParamters.Count > 0)
foreach (KeyValuePair<string, object> sqlParamter in sqlParamters)
_lastQuery = Regex.Replace(
_lastQuery,
"\\@" + sqlParamter.Key,
sqlParamter.Value.GetType() == typeof(int) || sqlParamter.Value.GetType() == typeof(decimal)
? sqlParamter.Value.ToString()
: "'" + sqlParamter.Value.ToString() + "'");
}
}
I want the function to do the parameter replace and ideally output something like this:
UPDATE StockUpdateQueue SET Synced = 1, SyncedAt = GETDATE() WHERE Id IN (12345,65432);
Any ideas?
Update
I use the sqlQuery and sqlParamters just as user un-lucky has shown, i.e.
{
mySqlCommand.Parameters.AddWithValue(sqlParamter .Key, sqlParamter.Value);
}
It turns out, I have been generating the dictionary keys without the @ and .NET has been automatically adding them for me (when they are missing - as explained by user juharr).
Sometimes, I generate the sql query and parameters dynamically - where the list of keys and their corresponding values were generated in a for/foreach loop. This resulted in a case of mix usage going on.
So, to handle this - I've updated my function like this and it's working as intended:
internal void LogLastQuery(string sqlQuery, Dictionary<string, object> sqlParamters = null)
{
_lastQuery = sqlQuery;
if (sqlParamters != null && sqlParamters.Count > 0)
foreach (KeyValuePair<string, object> sqlParamter in sqlParamters)
_lastQuery = Regex.Replace(
_lastQuery,
(sqlParamter.Key.ToString()[0] != '@' ? "\\@" : "") + sqlParamter.Key,
sqlParamter.Value.GetType() == typeof(int) || sqlParamter.Value.GetType() == typeof(decimal)
? sqlParamter.Value.ToString()
: "'" + sqlParamter.Value.ToString() + "'");
}
This now deals with both cases. I am not sure if this is the best method, but it works fine for now.