Club Delphi  
    Paypal   FTP   CCD     Buscar   Trucos   Trabajo   Foros

Retroceder   Foros Club Delphi > Bases de datos > Firebird e Interbase
Registrarse FAQ Miembros Calendario Guía de estilo Buscar Temas de Hoy Marcar Foros Como Leídos

Respuesta
 
Herramientas Buscar en Tema Desplegado
  #1  
Antiguo 09-04-2018
orodriguezca orodriguezca is offline
Miembro
 
Registrado: ene 2009
Posts: 221
Poder: 18
orodriguezca Va por buen camino
Cita:
Empezado por Angel.Matilla Ver Mensaje
Y, por cierto, ¿a qué collation te refieres?
Me refiero a que cuando se crea una tabla se puede definir el collation_name de cada una de las columnas de tipo carácter. El siguiente es un fragmento de la sintaxis de la sentencia Create Table:

CREATE TABLE
Used for: creating a new table (relation)
Available in: DSQL, ESQL

Syntax:
CREATE [GLOBAL TEMPORARY] TABLE tablename
[EXTERNAL [FILE] '<filespec>']
(<col_def> [, {<col_def> | <tconstraint>} ...])
[ON COMMIT {DELETE | PRESERVE} ROWS];

<col_def> ::= <regular_col_def> | <computed_col_def>

<regular_col_def> ::=
colname {<datatype> | domainname}
[DEFAULT {literal | NULL | <context_var>}]
[NOT NULL]
[<col_constraint>]
[COLLATE collation_name]

Si se trata de establecer una integridad referencial entre dos tabla, entre columnas varchar, y si las columnas varchar tienen diferente collation_name saltará el error: Partner index segment no 1 has incompatible data type

En preguntas frecuentes de Firebird se encuentra lo siguiente:

"Partner index segment no 1 has incompatible data type

This usually means that the field in the foreign key you're trying to create has a different data type then the field of the primary key column it is referencing.

The difference can be subtle, anything that affects index (even field collation) is taken info account.

To solve this problem, usually the right thing to do is to change the data type of the foreign key columns before creating the foreign key constraint.
"



Edito: De ser posible borrar (drop table, no delete) ambas tablas y vuelve a crearlas.
Responder Con Cita
  #2  
Antiguo 10-04-2018
Avatar de Angel.Matilla
Angel.Matilla Angel.Matilla is offline
Miembro
 
Registrado: ene 2007
Ubicación: Toledo - España
Posts: 1.418
Poder: 21
Angel.Matilla Va por buen camino
Gracias por la respuesta. No me había fijado en esa sintaxis; sin embargo, y haciendo caso a ecfisa, en la tabla DatLoc cambié el nombre de la columna por Codigo para que en ambas tablas se llamaran igual y tuvieran la misma estructura y por lo tanto en ambas ahora es: CodPrv VARCHAR(2) DEFAULT '99' NOT NULL, Codigo INTEGER NOT NULL, etc. Con esto la restricción quedaría así:
Código PHP:
ALTER TABLE DatLoc ADD CONSTRAINT FK_CodDatLoc FOREIGN KEY (CodPrvCodigoREFERENCES Poblacion(CodPrvCodigoON DELETE CASCADE ON UPDATE CASCADE 
Pero, a pesar de ello, se sigue generando el mismo error.

Sobre lo de eliminar la tabla y crearla de nuevo. Tengo el problema, que ya comenté ayer, que esa tabla Poblacion aplica restricciones en otras de la BB.DD. Estoy probando a borrar esas definiciones y crearlas de nuevo, pero no sé porqué (eso estoy investigando) no se ejecutan bien los querys.

Estoy haciendo esto, aunque empiezo a dudar que esté haciéndolo bien:
1. Tengo guardadas las definiciones en un array con la siguiente estructura:
Código PHP:
AnsiString cDefine[][3] = {{"CHK_ForPago" "Persona"   "ALTER TABLE Persona ADD CONSTRAINT CHK_ForPago CHECK (ForPago IN (SELECT Valor FROM Instalacion WHERE Etiqueta = 'ForPago'))"},
                           {
"CHK_PerPago" "Persona"   "ALTER TABLE Persona ADD CONSTRAINT CHK_PerPago CHECK (PerPago IN (SELECT Valor FROM Instalacion WHERE Etiqueta = 'PerPago'))"}, 
                           
etc
donde el primer elemento es el nombre de la restricción, el segundo el de la tabla sobre la que se aplica la misma y el tercero el código para crearla.
2. Verifico si existen todas las restricciones definidas en ese array.
Código PHP:
fMenu->Auxiliar->Close();
fMenu->Auxiliar->SQL->Text "SELECT * FROM RDB$CHECK_CONSTRAINTS WHERE RDB$CONSTRAINT_NAME = :Restriccion";

bool lPrueba true;
int nItem 0;
while (
cDefine[nItem][0] != "")
{
     
fMenu->Auxiliar->Close();
     
fMenu->Auxiliar->ParamByName("Restriccion")->AsString UpperCase(cDefine[nItem][0]);
     
fMenu->Auxiliar->Open();
     
lPrueba = !fMenu->Auxiliar->IsEmpty();
     if (!
lPrueba)
          break;
     
nItem ++;

3. De esta manera, si una de las restricciones que hay en el array no existe (lPrueba = false) es que hay que crearla y para curarme en salud intento borrar todas las que existen en ese momento. Para ello hago esto:
Código PHP:
fMenu->Auxiliar->Close();  // <-- Es el mismo query de más arriba
fMenu->Auxiliar->SQL->Text "SELECT * FROM RDB$CHECK_CONSTRAINTS WHERE RDB$CONSTRAINT_NAME = :Restriccion";

nItem 0;
while (
cDefine[nItem][0] != "")
{
     
fMenu->Auxiliar->Close();
     
fMenu->Auxiliar->ParamByName("Restriccion")->AsString UpperCase(cDefine[nItem][0]);
     
fMenu->Auxiliar->Open();

     if (!
fMenu->Auxiliar->IsEmpty())
     {
          try
          {
               
fMenu->Query->Close();
               
fMenu->Query->SQL->Text "ALTER TABLE " UpperCase(cDefine[nItem][1]) + " DROP CONSTRAINT " UpperCase(cDefine[nItem][0]);
               
fMenu->Query->ExecSQL();
               
fMenu->Query->Transaction->Commit();
          }
          catch(...)
          {
               
fMenu->Query->Transaction->Rollback();
          }
     }
     
nItem ++;

Veremos si así funcoona.
Responder Con Cita
Respuesta


Herramientas Buscar en Tema
Buscar en Tema:

Búsqueda Avanzada
Desplegado

Normas de Publicación
no Puedes crear nuevos temas
no Puedes responder a temas
no Puedes adjuntar archivos
no Puedes editar tus mensajes

El código vB está habilitado
Las caritas están habilitado
Código [IMG] está habilitado
Código HTML está deshabilitado
Saltar a Foro

Temas Similares
Tema Autor Foro Respuestas Último mensaje
Error al definir un FK en Firebird 2.5 Angel.Matilla Firebird e Interbase 10 29-11-2016 13:13:26
Error al intentar borrar constraint foreign key rfernandez Firebird e Interbase 5 08-10-2008 23:36:02
error al crear foreign key en firebird carlo_acp Conexión con bases de datos 2 23-02-2008 02:58:08
error de violation of foreign key constraint... en ibx Arturo Firebird e Interbase 1 07-12-2004 19:38:57
uso de FOREIGN KEY jzginez Firebird e Interbase 2 22-04-2004 23:20:25


La franja horaria es GMT +2. Ahora son las 17:51:58.


Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2026, Jelsoft Enterprises Ltd.
Traducción al castellano por el equipo de moderadores del Club Delphi
Copyright 1996-2007 Club Delphi