Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the SQL Server equivalent of Oracle bind variables in dynamic SQL?

In Oracle, when writing dynamic SQL one does something like this:

create or replace procedure myProc(n in number)
as
begin
  execute immediate
   'update myTable set myColumn = :n' 
   using n;
commit;
end;

And then 'magic happens'. What, if any, is the equivalent concept / syntax in SQL Server? (BTW I'm using SQL Server 2005)

like image 995
satnhak Avatar asked Aug 01 '11 12:08

satnhak


People also ask

How do you bind variables in dynamic SQL?

Rules for using bind variables with Execute Immediate of Native Dynamic SQL. In native dynamic SQL we need to list down the values for all the bind variables used in the SQL query beforehand. You cannot use schema object names such as table name as bind argument in native dynamic SQL.

What is bind variable in SQL server?

Bind variables are used by the SQL server to do a dynamic replacement of variables in an SQL statement. In some SQL servers this can increase query performance by allowing the server to compile and reuse the SQL compiled SQL query many times.

What is dynamic variable in SQL server?

Dynamic SQL is a programming technique where you build SQL query as a string and execute it dynamically at runtime. It lets you build the general-purpose query on the fly using variables, based on the requirements of the application. This makes a dynamic SQL more flexible as it is not hardcoded.

What is the another name for bind variable?

Bind parameters—also called dynamic parameters or bind variables—are an alternative way to pass data to the database.


1 Answers

You would use sp_executesql. The bound variables look like this: @var1.

From the below link, an example query against the standard Northwind database:

DECLARE @IntVariable int;
DECLARE @SQLString nvarchar(500);
DECLARE @ParmDefinition nvarchar(500);

/* Build the SQL string one time.*/
SET @SQLString =
     N'SELECT BusinessEntityID, NationalIDNumber, JobTitle, LoginID
       FROM AdventureWorks2008R2.HumanResources.Employee 
       WHERE BusinessEntityID = @BusinessEntityID';
SET @ParmDefinition = N'@BusinessEntityID tinyint';
/* Execute the string with the first parameter value. */
SET @IntVariable = 197;
EXECUTE sp_executesql @SQLString, @ParmDefinition,
                      @BusinessEntityID = @IntVariable;
/* Execute the same string with the second parameter value. */
SET @IntVariable = 109;
EXECUTE sp_executesql @SQLString, @ParmDefinition,
                      @BusinessEntityID = @IntVariable;

Full details and example syntax are at the following links:

http://msdn.microsoft.com/en-us/library/ms188001.aspx

http://msdn.microsoft.com/en-us/library/ms175170.aspx

like image 54
mwigdahl Avatar answered Oct 07 '22 23:10

mwigdahl