代码之家  ›  专栏  ›  技术社区  ›  Adam Lassek

是否可以将输出参数与ExecuteQuery一起使用?

  •  2
  • Adam Lassek  · 技术社区  · 17 年前

    通常,当您希望通过Linq直接调用存储过程到Sql时,可以使用ExecuteQuery方法:

    result = dc.ExecuteQuery<MyTable>("Exec myStoredProcedure");
    

    如果需要使用参数调用,可以通过字符串替换添加:

    string query = "Exec myStoredProcedure ";
    for (int i = 0; i < parameters.Count - 1; i++) {
      query += " {" + i + "},";
    }
    query = query.TrimEnd(',');
    result = dc.ExecuteQuery<MyTable>(query, parameters);
    

    但是如果其中一个参数是输出变量呢?程序运行后,是否有可能恢复该值?

    3 回复  |  直到 17 年前
        1
  •  1
  •   Conrad Frix    15 年前

    Alper Ozcetin是对的,您可以在*.dbml中映射StoredProcedures,并且可以使用StoredProcedures作为方法。

    下面是使用AdventureWorks DB执行此操作的演示,适用于vs2008和vs2010

    在AdventureWorks中,我创建了以下程序

    CREATE PROC sp_test (@City  Nvarchar(60) , @AddressID int out  )
    AS
    SELECT TOP 10 * FROM Person.Address where City = @City
    select  top 1  @AddressID  = AddressID FROM Person.Address where City = @City
    

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Data.Linq;
    
    namespace Test
    {
        class Program
        {
            static void Main(string[] args)
            {
    
    
                DataClasses1DataContext dc = new DataClasses1DataContext("SomeSQLConnection);
    
                int? AddressID = null;
                ISingleResult<sp_testResult> result = dc.sp_test("Seattle", ref AddressID);
    
                foreach (sp_testResult addr in result)
                {
                    Console.WriteLine("{0} : {1}", addr.AddressID, addr.AddressLine1);
                }
                Console.WriteLine(AddressID);
    
    
            }
        }
    }
    

    这将导致以下输出

    23 : 6657 Sand Pointe Lane
    91 : 7166 Brock Lane
    92 : 7126 Ending Ct.
    93 : 4598 Manila Avenue
    94 : 5666 Hazelnut Lane
    95 : 1220 Bradford Way
    96 : 5375 Clearland Circle
    97 : 2639 Anchor Court
    98 : 502 Alexander Pl.
    99 : 5802 Ampersand Drive
    13079
    

    您会注意到sp_测试方法的输入是 ref

        2
  •  0
  •   Maksym Gontar    17 年前

    我不确定,但您可以尝试在查询中声明变量,将其作为输出参数传递,然后选择它:

    //assuming you out parameter is integer
    string query = "DECLARE @OUT INT ";
    query += " Exec myStoredProcedure ";
    for (int i = 0; i < parameters.Count - 1; i++) {
      query += " {" + i + "},";
    }
    //assuming the output parameter is the last in the list
    query += " @OUT OUT ";
    //select value from out param after sp execution
    query += " SELECT @OUT"
    
        3
  •  0
  •   Alper    17 年前

    您不需要在ExecuteQuery中为StoredProcess编写原始SQL。您可以在*.dbml中映射StoredProcess,并且可以将StoredProcess用作方法。