如何在 Management Studio 中编写参数化查询?
在客户端应用程序中,我通常会这样做:
select * from table where Name = :Parameter
然后在执行查询之前,我会执行
:Parameter = 'John'
这些参数不是“搜索和替换”,而是传递到服务器的实际参数。由于我需要详细测试其中一些查询,因此如何在 Management Studio 中编写查询?
我想编写带有参数的查询并为参数赋予一个值。这怎么能做到呢?
更新:
为了消除此处的混乱,我添加了信息以更好地表达自己。
当我执行普通查询时,我在 sql server profiler 中看到
select * from table where Name = 'John'
,而当我执行参数化查询时,我看到:
exec sp_executesql N'select * from table
where Name = @P1',N'@P1 varchar(8000)','John'
这就是为什么我说它不是搜索和替换。
From a client application I tyipically do:
select * from table where Name = :Parameter
and then before executing the query I do
:Parameter = 'John'
These parameters are not a Search&Replace but real parameters passed to the server. Since I need to test some of those queries in detail, how can I write the query in management studio?
I want to write the query with parameters and give a value to the parameter. How can this be done?
Update:
To remove confusion here I add info to better express myseld.
when I execute a normal query I see in sql server profiler
select * from table where Name = 'John'
while when I execute a parametrized query I see this:
exec sp_executesql N'select * from table
where Name = @P1',N'@P1 varchar(8000)','John'
This is why I say it is not a search and replace.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
怎么样
How about something like
看来您更新时回答了自己的问题。
在这里重写,以供将来可能像我一样困惑的访客使用。以下是如何在 SSMS 中编写参数化查询。如果您想分析代码运行的参数化查询的执行计划,这会有所帮助。
Looks like you answered your own question when you updated it.
Rewriting here for future visitors who may be confused like I was. Below is how you write a parameterized query in SSMS. This helps if you want to analyze the execution plan for a parameterized query run by your code.
除了 Adriaan Stander 的回答之外,如果您在代码中使用 C#,您应该确保已通过封装传递
@parameter
。这是一个代码示例:此代码旨在为您提供一个想法,因此并不完整。
In addition to Adriaan Stander's answer, if you were using C# in your code for example, you should have ensured that you have passed the
@parameter
via encapsulating. Here is a code example:This code is intended to give you an idea and therefore isn't complete.