2012-09-25 50 views

回答

4

使用Threading.Tasks。下面的代碼會讓你的線程等待任務完成。

public void CallStoredProcMethod() 
{ 
    var task1 = System.Threading.Tasks.Task.Factory.StartNew(() => RunStoredPro()); 

    // thread will wait there till the operation finish 
    task1.Wait(); 
} 

public void RunStoredPro() 
{ 
    using (var connection = new SqlConnection(sqlConnString)) 
    { 
     // your database call 
    } 
} 
2

System.Data.Common.DbCommand有一個CommandTimeout財產。

獲取或設置在終止嘗試執行 命令並生成錯誤之前的等待時間。以秒爲單位等待命令執行的時間。注意實施者,建議0表示不超時。

請注意,SqlCommand的默認值是30秒。如果您將CommandTimeout屬性設置爲0,則只要存儲過程需要執行,您的調用就會執行。爲ExecuteScalar執行上一個SqlCommand在MSDN頁面下面的例子中,稍加修改設置CommandTimeout

static public int AddProductCategory(string newName, string connString) 
{ 
    Int32 newProdID = 0; 
    string sql = 
     "INSERT INTO Production.ProductCategory (Name) VALUES (@Name); " 
     + "SELECT CAST(scope_identity() AS int)"; 
    using (SqlConnection conn = new SqlConnection(connString)) 
    { 
     SqlCommand cmd = new SqlCommand(sql, conn); 

     // this will cause the command to wait until the sproc is finished 
     cmd.CommandTimeout = 0; 

     cmd.Parameters.Add("@Name", SqlDbType.VarChar); 
     cmd.Parameters["@name"].Value = newName; 
     try 
     { 
      conn.Open(); 
      newProdID = (Int32)cmd.ExecuteScalar(); 
     } 
     catch (Exception ex) 
     { 
      Console.WriteLine(ex.Message); 
     } 
    } 
    return (int)newProdID; 
} 
1

使用return語句中的存儲過程,並獲得價值

爲例如存儲過程

set ANSI_NULLS ON 
set QUOTED_IDENTIFIER ON 
go 

ALTER PROCEDURE [dbo].[Validate] 
@inputdata varchar(50), 
@outputdata varchar(50) output 

AS 
SET @outputdata = (
SELECT TOP 1 Password FROM dbo.tblUser WHERE Login = @a) 

RETURN @outputdata 
GO 

我在這裏簡要地解釋C#中的核心代碼

 string returnValue = string.Empty; 
     ............... 
     SqlConn.Open(); 
     sqlcomm.CommandType = CommandType.StoredProcedure; 
     SqlParameter param = new SqlParameter("@inputdata", SqlDbType.VarChar); 
     param.Direction = ParameterDirection.Input; 
     param.Value = Username; 
     sqlcomm.Parameters.Add(param); 

     SqlParameter retval = sqlcomm.Parameters.Add("@outputdata", SqlDbType.VarChar); 
     retval.Direction = ParameterDirection.Output; 
     string retunvalue = (string)sqlcomm.Parameters["@outputdata"].Value; 
     ...................... 
     .........