Is it possible to get the parsed text of a SqlCommand with SqlParameters?

∥☆過路亽.° 提交于 2019-11-28 11:58:27

You have a mistaken notion of how parameterized queries work. The "parsed text" you speak of is never created, and parameter values are never substituted directly into the query string.

That's why it's so important to use parameterized queries — you have complete segregation of query data from query code. Data is data, code is code, and never the twain shall meet. Thus, there is no possibility for sql injection.

What it means is that if you have a CommandText like this:

SELECT SomeColumn FROM SomeTable WHERE ID= @ID

instead of ultimately running a query that looks like this:

SELECT SomeColumn FROM SomeTable WHERE ID= 123

you actually run something more like this:

DECLARE @ID Int
Set @ID = RetrieveQueryDataItem("@ID")
SELECT SomeColumn FROM SomeTable WHERE ID= @ID

Now, this isn't exactly what happens; the engine doesn't transform the code like that. Instead, it uses the sp_executesql procedure. But this should help you understand what's going on.

Joel Coehoorn is right, it's not just a simple string substitution or escape character adding, etc.

You can, however, view your parameters to see if your values are as you want them:

foreach (IDataParameter i in cmd.Parameters)
{
    Console.WriteLine(i.Value.ToString());
}

THe SQLCommand object does not swap out the params for the value in the command text and run that. It calls the sp_execute sql with the exact text you supply and then supplies the list of paramaters. Use SQL profiler against a database and you will see what i mean.

What is it you are actually trying to acheive here?

I would be tempted to look into using LINQ as it will give you the control you want in your C# code.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!