How to write a parametrized query in management studio?

北战南征 提交于 2019-12-21 03:25:13

问题


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.


回答1:


How about something like

DECLARE @Parameter VARCHAR(20)
SET @Parameter = 'John'

SELECT *
FROM Table
WHERE Name = @Parameter



回答2:


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.

EXEC sp_executesql
N'

SELECT * FROM table_t 
WHERE first_name = @parameter

',
N'@parameter VARCHAR(8000)',
N'John'



回答3:


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 @parametervia encapsulating. Here is a code example:

using (SqlConnection conn = new SqlConnection(conString))
{
    conn.Open();

    SqlCommand cmd = new SqlCommand(userSql, conn);
    cmd.Parameters.AddWithValue("@parameter", parameter);


    conn.Close();

}

This code is intended to give you an idea and therefore isn't complete.



来源:https://stackoverflow.com/questions/4407070/how-to-write-a-parametrized-query-in-management-studio

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