【发布时间】:2019-07-01 19:09:55
【问题描述】:
我正在尝试使用 FireDAC 在 SQL Server 数据库中创建一个表。但是,FireDAC 没有使用我提供的索引名称,而是使用了错误的索引名称,从而引发了异常并且没有创建表。 我做错了吗?如果没有,是否有解决方法?
请注意,我将有效的数据库架构名称 cnf 用于 TableName。 我特别需要在架构中创建表。
最简单的测试用例:
var
Connection: TFDConnection;
Table: TFDTable;
begin
Connection := TFDConnection.Create(nil);
Table := TFDTable.Create(nil);
try
Connection.Params.Add ('DriverID=MSSQL');
Connection.Params.Add ('OSAuthent=No');
Connection.Params.Add ('User_Name=sa');
Connection.Params.Add ('Password=XXXXXX');
Connection.Params.Add ('Server=DAVE-DELL\MSSQLSERVER2016');
Connection.Params.Add ('Database=PROJECT_DB');
Connection.Params.Add ('MARS=No');
Connection.Open;
Table.Connection := Connection;
Table.TableName := 'cnf.TestTable';
Table.FieldDefs.Add ('TableID', ftAutoInc, 0, true);
Table.FieldDefs.Add ('Field1', ftInteger, 0, true);
Table.FieldDefs.Add ('Field2', ftstring, 100, true);
Table.IndexDefs.Add ('PK_XYZ', 'TableID', [ixPrimary]); // should use this index name!
Table.CreateTable (true);
finally
Table.Free;
Connection.Free;
end;
end;
引发异常:
[FireDAC][Phys][ODBC][Microsoft][SQL Server Native Client 11.0][SQL Server]Incorrect syntax near '.'.
运行 SQL Server Profiler 显示 FireDAC 正在尝试使用以下 SQL 代码创建索引:
ALTER TABLE temp.TestTable ADD CONSTRAINT [cnf].[PK_TestTable] PRIMARY KEY (TableID)
当然,[cnf].[PK_TestTable] 在 T-SQL 中不是一个有效的索引名称,这是问题的症结所在。
- 如果我删除
Table.IndexDefs.Add行,则表会正确创建,但没有索引。 -
如果我将该行替换为以下内容,则会出现同样的问题:
with Table.IndexDefs.AddIndexDef do begin Name := 'PK_XYZ'; Options := [ixPrimary]; Fields := 'TableID'; end; -
如果我将设置表名替换为以下内容,则会出现同样的问题:
Table.TableName := 'TestTable'; Table.SchemaName := 'cnf';
为什么它使用自己的(错误的)索引名称,而不是我给它的名称?(即PK_XYZ)
- Embarcadero® Delphi 10.1 柏林版 24.0.25048.9432
- SQL Server 2016 (SP2-CU4) - 13.0.5233.0 (X64)
【问题讨论】:
-
如果您使用 MS OleDB 驱动程序而不是 ODBC 驱动程序,您会得到相同的行为吗?
-
@Martyn 一个好建议 - 有机会我会检查的。
-
基于下面 Peter 的广泛回答,为什么不在这种情况下避免使用 FD 索引创建例程?在
ExecSQL('Alter Table ...')调用中创建索引 -
@JacalarRick 谢谢 - 我现在已经做到了,直到我可以进行更多实验。
标签: sql-server delphi firedac