2012-03-22 2 views
2

CLR 트리거가 있는데 이는 저장 프로 시저를 BeginInvoke으로 호출합니다. 저장 프로 시저에서 SqlComman을 호출하려고하는데 다음과 같이 나타납니다. 요청한 작업에 SQL Server 실행 스레드가 필요합니다. 현재 스레드는 사용자 코드 또는 기타 비 -Sql 서버 엔진 코드에 의해 시작되었습니다.CLR 저장 프로 시저에 Sql 서버 실행 스레드가 필요합니다.

SP에서이 작업을 수행해야하며 기다림으로 인해 BeginInvoke으로 SP를 호출해야합니다.

코드 :

[SqlProcedure()] 
public static void MySendData(String crudType, String sourceTable, ...) { 
    SqlCommand sqlDeleteComm; 

    String temp = String.Empty; 

    using(SqlConnection conn = new SqlConnection("context connection=true")) { 

     sqlDeleteComm = new SqlCommand("DELETE FROM #TEMP_TABLE"); 
     sqlDeleteComm.Connection = conn; 

     try { 
      conn.Open(); 
      sqlDeleteComm.ExecuteNonQuery(); 
      conn.Close(); 
     } catch(Exception ex) { 
      // --- here --- 
      // The requested operation requires a Sql Server execution thread. The current thread was started by user code or other non-Sql Server engine code. 
     } 
    } 
    ... 
} 

[Microsoft.SqlServer.Server.SqlTrigger(Name = "MyTrigger", Target = "MyTable", Event = "FOR UPDATE, INSERT, DELETE")] 
public static void MyTrigger() { 
    SqlTriggerContext myContext = SqlContext.TriggerContext; 
    MyDelagate d; 
    SqlCommand sqlComm; 
    SqlDataReader reader; 

    if(connection.State != ConnectionState.Open) { 
     connection.Open(); 
    } 

    switch(myContext.TriggerAction) { 
     case TriggerAction.Update: 
      sqlComm = new SqlCommand("SELECT X, Y FROM Inserted"); 
      sqlComm.Connection = connection; 

      reader = sqlComm.ExecuteReader(); 
      try { 
       reader.Read(); 
       d = new MyDelagate(MySendData); 
       d.BeginInvoke("Update", "MyTable", (Int32)reader[ 0 ], (Int32)reader[ 1 ], null, null); 
      } catch(Exception ex) { 
      } finally { 
       reader.Close(); 
      } 
      break; 
      ... 
    } 
} 

어떻게 수 I의 SP에 SQL 쿼리를 호출하는 모든 하시나요?

답변

1

스레드 외부에서 컨텍스트 연결을 사용할 수 없습니다. SQL Server에서 CLR 코드를 실행합니다. 이것은 서버의 안정성을 보장하는 것입니다 - SQL Server는 사용자 지정 CLR 호스팅을 사용하며, 자신의 스레드를 전혀 돌릴 수 없었던 것은 놀랍습니다. 문맥 SqlConnection에서 표준 ADO.NET SqlCommand을 사용하여 MySendDataMyTrigger에서 T-SQL로 호출 할 수 있지만 별도의 스레드에서 실행할 수는 없습니다. 데이터베이스 수준에서 비동기/병렬을 원한다면 SQL Server Broker를 살펴보십시오.