sql-server - SQL Server 中动态 SQL 中 Oracle 绑定(bind)变量的等价物是什么?

标签 sql-server tsql dynamic-sql

在 Oracle 中,编写动态 SQL 时会执行以下操作:

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

然后“奇迹发生了”。 SQL Server 中的等效概念/语法(如果有)是什么? (顺便说一句,我使用的是 SQL Server 2005)

最佳答案

您将使用sp_executesql。绑定(bind)变量如下所示:@var1

下面的链接是针对标准 Northwind 数据库的示例查询:

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;

完整的详细信息和示例语法位于以下链接:

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

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

关于sql-server - SQL Server 中动态 SQL 中 Oracle 绑定(bind)变量的等价物是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6898611/

相关文章:

C#如何实现返回SQL结果列表的方法?

sql - 在 SQL Server 2008 中使用列别名指定数据类型

mysql - 了解 SQL 别名

oracle - 如何使用动态列取消透视 Oracle

C# Nhibernate 保存列表

sql - 在 sql 中按月份和年份排序并求和

sql-server - 将一列相加并减去第二列

sql-server - 将多行默认值插入表中

sql - 我可以在 SQL Server/TSQL 中回滚动态 SQL

postgresql - 如何在postgres中执行存储过程的字符串结果