I'm going to assume that you are trying to run a SQL query from some client code by passing in variables with the query, though I'm not sure of this or what language you might be using - please clarify and add tags so we can help.
SQL Server does not use ?
for parameter placeholders like in other DBMS queries (say, SQLite which uses ?
in the way you are trying to use them). Instead, you need to either let an ORM tool declare variables for you, and use those, or explicitly declare your own parameters and pass them in. You haven't told us the development environment you're using or what method of SQL connection and ORM (if any) you're using, but here's a quick example using the very excellent Dapper ORM in C# from here, given an open connection conn
:
string val = "my value";
conn.Execute("insert MyTable (val) values(@val)", new {val});
// or: conn.Execute("insert MyTable (val) values(@val)", new {val = val});"
conn.Execute("update MyTable set val = @val where Id = @id", new {val, id = 1});
In the background, Dapper handles the mapping and creation of variables, such that the actual SQL script received by SQL Server is something closer to this:
-- first query:
declare @val nvarchar(max) = 'my value';
insert MyTable (val) values(@val);
-- second query:
declare @val nvarchar(max) = 'my value', @id int = 1;
update MyTable set val = @val where Id = @id
On the other hand, if you are just going to execute a raw query directly with a SqlConnection
, try something like this (equivalent to the first query above):
// Assumes an open connection conn
string val = "my value";
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "insert MyTable (val) values(@val)";
cmd.Parameters.AddWithValue("@val", val); // This creates the @val declaration for you when the query is executed
cmd.ExecuteNonQuery();
}
Whatever you do, parameterize your parameters, and beware of SQL injection!
Hope that helps. If you'd like a clearer example, please give us some code to show how you're passing the query to the SQL Connection for execution.