如何使用在交易中创建的新表

时间:2018-10-20 10:58:05

标签: sql delphi

当我在事务内创建表时,该表在事务中不可访问,但在事务之前创建的所有其他表均可访问。 我该如何解决这个问题?

procedure TForm1.Button1Click(Sender: TObject);
var MyAdo:TADOQuery;
    a,b:integer;
begin
  AdoConnection1.ConnectionString := 'Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=master;Data Source=MyPCNAME'
  MyAdo:=TAdoQuery.Create(Application);
  MyAdo.Connection := ADOConnection1;
  MyAdo.SQL.Add('Create table tempdb..test1 (TBID int) '
              +' Insert Into tempdb..test1 Values (1) '
              +' Insert Into tempdb..test1 Values (2) '
               );
  MyAdo.ExecSQL;

  ADOConnection1.BeginTrans;

  MyAdo.SQL.Clear;
  MyAdo.SQL.Add('Create table tempdb..test2 (TBID int) ');
  MyAdo.ExecSQL;


  MyAdo.SQL.Clear;
  MyAdo.SQL.Add('Select max(TBID) Mx1 From TempDb..Test1 ');
  MyAdo.Open;
  A:=MyAdo.FieldByName('Mx1').AsInteger;        //Result:2

  MyAdo.SQL.Clear;
  MyAdo.SQL.Add('Select max(TBID) Mx2 From TempDb..Test2 ');
  MyAdo.Open;
  B:=MyAdo.FieldByName('Mx2').AsInteger;        //Deadlock!!!!!!!!! It need to force the application to close

  ADOConnection1.CommitTrans;
end;

1 个答案:

答案 0 :(得分:1)

尝试如下更改代码

  [...]
  MyAdo.Close;
  MyAdo.SQL.Clear;
  MyAdo.SQL.Add('Select max(TBID) Mx2 From TempDb..Test2 with (nolock)');
  MyAdo.Open;
  B:=MyAdo.FieldByName('Mx2').AsInteger;   //  No Deadlock

这对我有效,但不阻止SS2014。但我认为,从f.i.开始,您可能最好阅读该主题。 SQL Server SELECT statements causing blocking

顺便说一句,与在q中所说的相反,将AdoConnection的IsolationLevel设置为ilReadUncommitted并不能避免原始代码的阻塞。