Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server: How to write and execute a prepared statement? [closed]

In MySQL, we can generate the prepared statement using PreparedStatement.

I want to achieve the same functionality in SQL script. How to create the prepared statement and how to execute it? Please provide an example for that.

like image 789
Tausif Avatar asked Aug 16 '12 09:08

Tausif


People also ask

How do I run a PreparedStatement in SQL Server?

Execute a statement—The application sends a SQL statement (for example, SELECT * FROM table WHERE ...) to the database server via the driver. Fetch rows—The driver retrieves all the values of all the result columns from the database server because the driver doesn't know which values the application will request.

Does PreparedStatement need to be closed?

Closing PreparedStatement Object A simple call to the close() method will do the job. If you close the Connection object first, it will close the PreparedStatement object as well. However, you should always explicitly close the PreparedStatement object to ensure proper cleanup.

Can I reuse a PreparedStatement?

Once a PreparedStatement is prepared, it can be reused after execution. You reuse a PreparedStatement by setting new values for the parameters and then execute it again.


1 Answers

I would suggest using sp_executesql over exec for most dynamic SQL. sp_executesql is similar to MySQL's EXECUTE...USING in that it can take parameters rather than only concatenated strings, thus giving you a good defense against SQL injection. sp_executesql also allows SQL Server to reuse the query plan for more efficient querying. Here's an example:

exec sp_executesql
    @statement = N'select * from sys.databases where name = @dbname or database_id = @dbid',
    @parameters = N'@dbname sysname, @dbid int',
    @dbname = N'master',
    @dbid = 1

Some more info and examples can be found here.

like image 118
Tim Lehner Avatar answered Sep 27 '22 22:09

Tim Lehner