SQLite:将字符串转换为Date

问题描述 投票:0回答:1

我试图将字符串中的datetime转换为2017年12月11日00:00:00 AM到SQLite中的YYYY-MM-DD格式。这些表最初是在Oracle中,因此to_date()能够将文本转换为日期。但是我如何在SQLite中实现这一目标? date和strftime函数无法将月份作为转换文本。

谢谢!

sqlite date-formatting
1个回答
0
投票

你必须通过代码来实现它(DELPHI):

主要过程:

procedure TfrmMain.btn2Click(Sender: TObject);
var
  DB: TSQLite3Database;//helper class
  Stmt: TSQLite3Statement;//helper class
begin
  DB := TSQLite3Database.Create;
  DB.Open(ExtractFilepath(application.exename) + 'YourDB.db3');

  // here you set the function that will SQLite use to call in the query
  DB.fnTO_MouliTr_DATE;

  // prepare statement and fire it after 
  Stmt :=  DB.Prepare('update YourTable set NewDate = TO_MouliTr_DATE(NewDate)');

  Stmt.Step;

  Stmt.Free;
end;

调用sqlite3_create_function_v2

procedure TSQLite3Database.fnTO_MouliTr_DATE;
begin
  sqlite3_create_function_v2(FHandle, 'TO_MouliTr_DATE', 1 , SQLITE_ANY, nil,InternalSQLFunctionTO_MouliTr_DATE,nil,nil, nil);
end;

最后将完成工作的程序

procedure InternalSQLFunctionTO_MouliTr_DATE(ctx: PSQLite3Context; n: Integer; apVal:
    PPSQLite3ValueArray); cdecl;

var StartPos: integer;
  s1: string;
  DT: TDateTime;

begin
  case n of
    1: StartPos := 1;
  else
    begin
      raise ESQLite3Error.Create('The TO_MouliTr_DATE function requires 1 argument.');
      exit;
    end;
  end;
  if (sqlite3_value_type(apVal[0])=SQLITE_NULL) then
    sqlite3_result_text(ctx, PAnsiChar(''), Length(''), SQLITE_TRANSIENT)
  else
  begin

    s1 := sqlite3_value_text(apVal[0]);

    // HERE YOUR LOGIC
    DT := StrToDateTime(s1);

    s1 := FormatDateTime('yyyy-mm-dd', DT);

    sqlite3_result_text(ctx, PAnsiChar(s1), Length(s1), SQLITE_TRANSIENT);

  end;
end;

不幸的是,这个不会完成工作,因为StrToDateTime无法将给定的字符串转换为日期时间,但我只是想指出你应该针对你的问题的方向。

希望这会有所帮助

© www.soinside.com 2019 - 2024. All rights reserved.