sql-server - 根据ADO提供程序格式化日期

标签 sql-server delphi ms-access delphi-2010 ado

我有一个使用ADO的Delphi 2010应用程序来支持可以是SQL Server或MS Access的数据库。使用参数化查询将SQL发送到数据库时,可以正确处理日期表示形式的差异。但有时我需要形成动态SQL并将其发送到数据库。

有什么方法可以让TADOConnection将我的日期格式化为适合当前数据库的文本字符串,或者询问连接以了解如何格式化日期?否则,我将无法构建提供程序名称和日期格式功能表。

最佳答案

您还应该能够将参数与动态sql一起使用。我已经在自己的OPF框架的多个版本中做到了这一点。

只需使用参数编写SQL语句,然后将其作为字符串分配给TAdoQuery(或TAdoCommand)的SQL文本。然后,组件应解析您的文本并为您设置参数集合。之后,您应该能够将值分配给您的参数并调用Open或Execute...。

给您一个想法:

  DS := DatasetClass.Create( self.Connection );
  try
    DS.QueryText := SQL.Text;
    FillSelectParams( DS );
    DS.Open;
    try
      ...
    finally
      DS.Close;
    end;
  finally
    DS.Free;
  end;


在其中FillSelectParams调用以下FillParams过程:

procedure TSQLDataManager.FillParams(ADS: TCustomDataset);
var
  i: integer;
  ParamName: string;
  Attr: TCustomDomainAttribute;
  Ref: TCustomDomainObject;
  Value: Variant;
begin
  for i := 0 to ADS.ParamCount - 1 do begin
    Value := Null;
    ParamName := ADS.ParamName[i];
    if ParamName = 'Id' then begin
      ParamName := 'Identity';
    end;
    Attr := CDO.AttrByName[ParamName];
    if Attr <> nil then begin
      Value := ADS.AdjustParamValue( Attr );
    end else begin
      Ref := CDO.ReferenceByName[ParamName];
      if ( Ref <> nil ) and ( Ref.Identity <> C_UnassignedIdentity ) then begin
        Value := Ref.Identity;
      end;
    end;
    if Value <> Null then begin
      ADS.ParamValue[i] := Value;
    end;
  end;
end;


在这种情况下,参数值取自自定义域对象(CDO),但是您可以在此处替换您自己的样式。

AdjustParamValue函数负责几次转换。它已在所使用的TCustomDataSet类后代的ADO版本中实现,以处理具有不同TDataSet后代的组件变化,但是SQL数据库类型没有作用:

function TADODCDataset.AdjustParamValue(Attr: TCustomDomainAttribute): Variant;
begin
  if Attr is TIdentityAttribute then begin
    if Attr.AsInteger = 0 then begin
      Result := Null;
    end else begin
      Result := Attr.Value;
    end;
  end else if Attr is TBooleanAttribute then begin
    if Attr.AsBoolean then begin
      Result := Integer( -1 );
    end else begin
      Result := Integer( 0 );
    end;
  end else if Attr is TDateTimeAttribute then begin
    if Attr.AsDateTime = 0 then begin
      Result := Null;
    end else begin
      Result := Attr.Value;
    end;
  end else if Attr is TEnumAttribute then begin
    Result := Attr.AsString
  end else begin
    Result := Attr.Value;
  end;
end;

关于sql-server - 根据ADO提供程序格式化日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4684987/

相关文章:

sql - 计算跨越多个日期范围的记录

sql - 选择已分组的 2 条记录,然后将它们并排放置在 2 列中

sql-server - 在 SET 中使用通配符

sql - 在存储过程中构建动态 WHERE 子句

delphi - CreateWnd 和 CreateWindowHandle 有什么区别?

sql - From 子句中的语法错误使用 ADO 删除记录

forms - 当表单没有焦点时,如何防止表单处理热键?

delphi - 如何在其自身事件中释放控件?

javascript - 无法修复网页上的 VBA 爬网错误

sql - 如何在 MS Access 查询中指定默认值?