【问题标题】:What is the SQL Server equivalent of Oracle bind variables in dynamic SQL?动态 SQL 中的 Oracle 绑定变量的 SQL Server 等效项是什么?
【发布时间】:2023-03-06 15:31:01
【问题描述】:

在 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)

【问题讨论】:

    标签: sql-server tsql dynamic-sql


    【解决方案1】:

    您将使用sp_executesql。绑定的变量如下所示:@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

    【讨论】:

      【解决方案2】:

      sp_executeSQL可能是最接近的,还有exec(),还有必读:The Curse and Blessings of Dynamic SQL

      【讨论】:

        猜你喜欢
        • 2011-04-01
        • 2019-09-01
        • 2011-06-26
        • 2012-05-30
        • 2016-12-22
        • 2010-11-19
        • 1970-01-01
        • 2020-03-02
        • 1970-01-01
        相关资源
        最近更新 更多