Foros Club Delphi

Foros Club Delphi (https://www.clubdelphi.com/foros/index.php)
-   MS SQL Server (https://www.clubdelphi.com/foros/forumdisplay.php?f=23)
-   -   duda de Update usando label.caption (https://www.clubdelphi.com/foros/showthread.php?t=95940)

giantonti1801 03-11-2022 01:16:21

duda de Update usando label.caption
 
Buena noche no logro congeniar con esta formula:
Quiere hacer un Update en la base de dato SQL de algunos campo:
Código:

        begin
        ADOQueryUpdate.SQL.Clear;
        ADOQueryUpdate.SQL.Add( 'UPDATE Tiket SET' );
        ADOQueryUpdate.SQL.Add( 'Estatus = 'OLD');
        ADOQueryUpdate.SQL.Add(' WHERE Item = ' +Trim(Label3.Caption));
        ADOQueryUpdate.ExecSQL;
        //ADOQueryUpdate.Refresh;
        end;

el acxion se ejecuta con un Speedbuton

En el label3 tengo el numero de registro dentro de la base de datos llamado ITEM, esta imformacion es traida por otra consulta SQL la cual Funciona sin ningun problema.
Lo que pretendo hacer es hacer un UPDATE de la tabla TIKET donde le cambio el valor que tiene el campo ESTATUS a 'OLD' especificamente del registro contenido dentro de Label3.caption, Claro esta que tebo modificar otros campos tambien con la misma condicion todos contenidos en los label.caption. pero ahora queria probar con uno solo y si funcionaba le agtregaba lo demas. Al momento de ejecutarlo me da un error que dice que no consigue el campo OLD.
Aqui donde digo yo, 'los misterios del SQL son infinito'.....:D:D:D:D

dec 03-11-2022 08:34:01

Hola a todos,

Si no me equivoco, lo que ocurre es que las comillas no están bien utilizadas, al menos en esta parte:

Código Delphi [-]
ADOQueryUpdate.SQL.Add( 'Estatus = 'OLD');

De hecho... no sé cómo te compila eso... pero en fin, sea como sea, creo que al menos esa parte de la consulta debería quedar así:

Código Delphi [-]
ADOQueryUpdate.SQL.Add( 'Estatus = "OLD"');

... puesto que el error se refiere a que se está usando "OLD" literalmente, como si fuese el nombre de un "campo", y, por eso no encuentra ese "campo". En la posible solución "OLD" se encierra entre comillas, de modo que ya no se trata de un "campo", sino del valor que le quieres dar al campo "Estatus".

Investiga en todo caso sobre cómo "parametrizar" consultas SQL en Delphi, puesto que considero que se evitan problemas de este tipo y se obtienen mejores garantías de que las consultas van a funcionar y además las propias consultas quedan "más elegantes".

kuan-yiu 03-11-2022 08:39:38

Comillas.
Código Delphi [-]
ADOQueryUpdate.SQL.Add( 'Estatus = 'OLD');
Código Delphi [-]
ADOQueryUpdate.SQL.Add( 'Estatus = "OLD" ');
ADOQueryUpdate.SQL.Add( 'Estatus = ' +QuotedStr('OLD'));
Y de paso parametriza, que siempre es buena idea:
Código Delphi [-]
ADOQueryUpdate.SQL.Add(' WHERE Item =:valor');
 ParamByName('valor').AsString := Trim(Label3.Caption);

dec 03-11-2022 09:16:25

Hola a todos,

Cita:

Empezado por kuan-yiu (Mensaje 548930)
Y de paso parametriza, que siempre es buena idea:
Código Delphi [-]
ADOQueryUpdate.SQL.Add(' WHERE Item =:valor');
 ParamByName('valor').AsString := Trim(Label3.Caption);

¡Haz caso a quien sabe! :)

giantonti1801 03-11-2022 11:53:06

Cita:

Empezado por kuan-yiu (Mensaje 548930)
Comillas.
Código Delphi [-]
ADOQueryUpdate.SQL.Add( 'Estatus = 'OLD');
Código Delphi [-]
ADOQueryUpdate.SQL.Add( 'Estatus = "OLD" ');
ADOQueryUpdate.SQL.Add( 'Estatus = ' +QuotedStr('OLD'));
Y de paso parametriza, que siempre es buena idea:
Código Delphi [-]
ADOQueryUpdate.SQL.Add(' WHERE Item =:valor');
 ParamByName('valor').AsString := Trim(Label3.Caption);

Gracias por responder amigo:
Aun no me rindo, pero aun tampoco tengo la solucion colocando el codigo tal cual tu mencionaste me da un erro que lo voy a adjuntar

Código:

begin
        Close;
        ADOQueryUpdate.SQL.Clear;
        ADOQueryUpdate.SQL.Add( 'UPDATE Tiket SET');
        ADOQueryUpdate.SQL.Add( 'Estatus = "OLD" ');
        ADOQueryUpdate.SQL.Add( 'Estatus = ' +QuotedStr('OLD'));
        ADOQueryUpdate.SQL.Add(' WHERE Item =:valor');
        ADOQueryUpdate.Parameters.ParamByName('Valor').Value := StrToInt(Label3.Caption);
        ADOQueryUpdate.ExecSQL;
        end;

Hay una cosa que no entiendo del código y talvez alli el error
Código Delphi [-]
ADOQueryUpdate.SQL.Add(' WHERE Item =:valor');
yo no temg ningún campo o resultado que se llame 'valor', por lo que puedo asumir que este 'valor' sea una constante que abajo se le esta pasando el valor contenido en el Label3.caption, y de ser asi en el futuro tengo que hacer lo mismo con cada campo a la cual le voy a pasar el valor de un label?

Yo no se y quiero entender como una instrucion tan simple el SQL
Código SQL [-]
 Update Tiket set Estatus = 'NEW' Where Item = '2'
donde solo quiero cambiar el valor que esta en el 2 y colocarle un valor contenido en un label se ha convertido en un problema

kuan-yiu 03-11-2022 12:01:22

Puse dos opciones para la misma linea, jeje, no tienes que usar las dos, sino la que prefieras: con comillas o con QuotedStr (que es la que a mi me gusta más).
Por eso te da error, piensa que son dos campos y espera una coma en medio.

giantonti1801 03-11-2022 12:19:27

Cita:

Empezado por kuan-yiu (Mensaje 548939)
Puse dos opciones para la misma linea, jeje, no tienes que usar las dos, sino la que prefieras: con comillas o con QuotedStr (que es la que a mi me gusta más).
Por eso te da error, piensa que son dos campos y espera una coma en medio.


Si puedo entender eso pero a cual te refiere, talvez seria de ayuda si escribiera el codigo tal cual como deberia ir.

Muchas gracias por tu ayuda

giantonti1801 03-11-2022 12:44:16

Cita:

Empezado por giantonti1801 (Mensaje 548940)
Si puedo entender eso pero a cual te refiere, talvez seria de ayuda si escribiera el codigo tal cual como deberia ir.

Muchas gracias por tu ayuda

Listo, ya con tu ayuda pude resolver el problema, muchissimas gracias....

Código Delphi [-]
begin
        Close;
        ADOQueryUpdate.SQL.Clear;
        ADOQueryUpdate.SQL.Add( 'UPDATE Tiket SET');
        ADOQueryUpdate.SQL.Add( 'Estatus = ' +QuotedStr('OLD'));
        ADOQueryUpdate.SQL.Add(' WHERE Item =:valor');
        ADOQueryUpdate.Parameters.ParamByName('Valor').Value := StrToInt(Label3.Caption);
        ADOQueryUpdate.ExecSQL;
        end;

Para ayudar a otros foreros que tengan el mismo problema el codigo quedo Asi.

giantonti1801 03-11-2022 14:45:22

Cita:

Empezado por giantonti1801 (Mensaje 548941)
Listo, ya con tu ayuda pude resolver el problema, muchissimas gracias....

Código Delphi [-]
begin
        Close;
        ADOQueryUpdate.SQL.Clear;
        ADOQueryUpdate.SQL.Add( 'UPDATE Tiket SET');
        ADOQueryUpdate.SQL.Add( 'Estatus = ' +QuotedStr('OLD'));
        ADOQueryUpdate.SQL.Add(' WHERE Item =:valor');
        ADOQueryUpdate.Parameters.ParamByName('Valor').Value := StrToInt(Label3.Caption);
        ADOQueryUpdate.ExecSQL;
        end;

Para ayudar a otros foreros que tengan el mismo problema el codigo quedo Asi.

Pueden indicarme como hacer ahora para agregar mas informacion? es decir tengo que dentro del mismo update cambiar otros campos que estan igual en otro label

Casimiro Notevi 03-11-2022 14:51:23

Código SQL [-]
update tabla1 set campo1=aaa, campo2=bbb, campo3=ccc where...

giantonti1801 03-11-2022 15:13:42

Cita:

Empezado por Casimiro Notevi (Mensaje 548945)
Código SQL [-]
update tabla1 set campo1=aaa, campo2=bbb, campo3=ccc where...

y no tengo que colocarle ningun ParamByName?
[sql]update tabla1 set campo1=+label1.caption, campo2=+label2,caption, campo3=+label3.caption [sql] Asi?

cloayza 03-11-2022 15:55:38

Cita:

Empezado por giantonti1801 (Mensaje 548944)
Pueden indicarme como hacer ahora para agregar mas informacion? es decir tengo que dentro del mismo update cambiar otros campos que estan igual en otro label

Me tomé la libertad de usar el mismo código del colega giantonti1801, he incorporé otros atributos...

En mi opinión y por claridad, los parametros deberian tener el mismo nombre de los campos a actualizar. Por supuesto eso queda a criterio y gusto del colega...

Código Delphi [-]
        
        Close;
        ADOQueryUpdate.SQL.Clear;
        ADOQueryUpdate.SQL.Add( 'UPDATE Tiket'
        ADOQueryUpdate.SQL.Add( 'SET ');
    ADOQueryUpdate.SQL.Add( 'Estatus =:Estatus,');
    ADOQueryUpdate.SQL.Add( 'Nombre  =:Nombre,');
    ADOQueryUpdate.SQL.Add( 'Apellido=:Apellido,');
    ADOQueryUpdate.SQL.Add( 'Edad    =:Edad');
    ADOQueryUpdate.SQL.Add(' WHERE Item =:Item');
    
        //Asignación de valores a los parametros...  
    //Precaución con los tipos de datos
    ADOQueryUpdate.Parameters.ParamByName('Estatus').Value :='OLD';
    ADOQueryUpdate.Parameters.ParamByName('Nombre').Value  :='Merluso';
    ADOQueryUpdate.Parameters.ParamByName('Apellido').Value:='Boric';
    ADOQueryUpdate.Parameters.ParamByName('Edad').Value    :=19;
        ADOQueryUpdate.Parameters.ParamByName('Item').Value    := StrToInt(Label3.Caption);
        ADOQueryUpdate.ExecSQL;
        end;

Saludos cordiales

giantonti1801 03-11-2022 16:13:27

Cita:

Empezado por cloayza (Mensaje 548947)
Me tomé la libertad de usar el mismo código del colega giantonti1801, he incorporé otros atributos...

En mi opinión y por claridad, los parametros deberian tener el mismo nombre de los campos a actualizar. Por supuesto eso queda a criterio y gusto del colega...

Código Delphi [-]
        
        Close;
        ADOQueryUpdate.SQL.Clear;
        ADOQueryUpdate.SQL.Add( 'UPDATE Tiket'
        ADOQueryUpdate.SQL.Add( 'SET ');
    ADOQueryUpdate.SQL.Add( 'Estatus =:Estatus,');
    ADOQueryUpdate.SQL.Add( 'Nombre  =:Nombre,');
    ADOQueryUpdate.SQL.Add( 'Apellido=:Apellido,');
    ADOQueryUpdate.SQL.Add( 'Edad    =:Edad');
    ADOQueryUpdate.SQL.Add(' WHERE Item =:Item');
    
        //Asignación de valores a los parametros...  
    //Precaución con los tipos de datos
    ADOQueryUpdate.Parameters.ParamByName('Estatus').Value :='OLD';
    ADOQueryUpdate.Parameters.ParamByName('Nombre').Value  :='Merluso';
    ADOQueryUpdate.Parameters.ParamByName('Apellido').Value:='Boric';
    ADOQueryUpdate.Parameters.ParamByName('Edad').Value    :=19;
        ADOQueryUpdate.Parameters.ParamByName('Item').Value    := StrToInt(Label3.Caption);
        ADOQueryUpdate.ExecSQL;
        end;

Saludos cordiales

Perfecto pero estos valores estan contenidos en ul label2.capcion, ahora no se como colocarlo alli

Casimiro Notevi 03-11-2022 16:27:11

Cita:

Empezado por giantonti1801 (Mensaje 548948)
Perfecto pero estos valores estan contenidos en ul label2.capcion, ahora no se como colocarlo alli

Código Delphi [-]
ADOQueryUpdate.Parameters.ParamByName('Estatus').Value := labelelquesea.caption;
ADOQueryUpdate.Parameters.ParamByName('Nombre').Value  := labelotra.caption;
ADOQueryUpdate.Parameters.ParamByName('Apellido').Value:= labelyoquese.caption;

No estaría de más que le echaras un vistazo a este libro, te abrirá los ojos.

giantonti1801 03-11-2022 18:06:14

Cita:

Empezado por Casimiro Notevi (Mensaje 548949)
Código Delphi [-]
ADOQueryUpdate.Parameters.ParamByName('Estatus').Value := labelelquesea.caption;
ADOQueryUpdate.Parameters.ParamByName('Nombre').Value  := labelotra.caption;
ADOQueryUpdate.Parameters.ParamByName('Apellido').Value:= labelyoquese.caption;

No estaría de más que le echaras un vistazo a este libro, te abrirá los ojos.


Ahora me esta dando otro error no logro identificarlo

Código Delphi [-]
Close;
        ADOQueryUpdate.SQL.Add( 'UPDATE Tiket');
        ADOQueryUpdate.SQL.Add( 'SET');
        ADOQueryUpdate.SQL.Add( 'Estatus =:Estatus,');
        ADOQueryUpdate.SQL.Add( 'Usuario  =:Usuario,');
        ADOQueryUpdate.SQL.Add(' WHERE Item =:Item');
        //Asignación de valores a los parametros...
        //Precaución con los tipos de datos
        ADOQueryUpdate.Parameters.ParamByName('Item').Value := StrToInt(Label3.Caption);
        ADOQueryUpdate.Parameters.ParamByName('Estatus').Value :='OLD';
        ADOQueryUpdate.Parameters.ParamByName('Usuario').Value := Label4.caption;

        ADOQueryUpdate.ExecSQL;

NOTA: Error ' Incorrect Syntax near the 'WHERE'

cloayza 03-11-2022 19:14:51

Según el siguiente ejemplo que usted indicó...
Código SQL [-]
Update Tiket set Estatus = 'NEW' Where Item = '2'

Item= Es de tipo STRING

Y lo estas convirtiendo a entero...

Código Delphi [-]
ADOQueryUpdate.Parameters.ParamByName('Item').Value := StrToInt(Label3.Caption);

Lo que se traduce en una instrucción como la que sigue...
Código SQL [-]
Update Tiket set Estatus = 'NEW' Where Item = 2

Ese debe ser el origen del error

Verifique los tipos de datos...como mencione antes...

Saludos cordiales

giantonti1801 03-11-2022 20:10:17

Cita:

Empezado por cloayza (Mensaje 548954)
Según el siguiente ejemplo que usted indicó...
Código SQL [-]
Update Tiket set Estatus = 'NEW' Where Item = '2'

Item= Es de tipo STRING

Y lo estas convirtiendo a entero...

Código Delphi [-]
ADOQueryUpdate.Parameters.ParamByName('Item').Value := StrToInt(Label3.Caption);

Lo que se traduce en una instrucción como la que sigue...
Código SQL [-]
Update Tiket set Estatus = 'NEW' Where Item = 2

Ese debe ser el origen del error

Verifique los tipos de datos...como mencione antes...

Saludos cordiales

Código Delphi [-]
ADOQuery1Item: TAutoIncField;

Es autonumerico pero lo que debo hacer es solo leerlo pero entonces el problema puede ser que venga de aqui ya que es este punto yo le estoy pasando el valor ITEM para luego leerlo
Código Delphi [-]
Label3.Caption := ADOQuery1.fieldbyname('MINIMO').asstring;
[/delphi]
ADOQueryUpdate.SQL.Add( 'WHERE Item =:Item,');
ADOQueryUpdate.Parameters.ParamByName('Item').Value := StrToInt(Label3.Caption);
[/delphi]

giantonti1801 03-11-2022 20:46:04

Cita:

Empezado por giantonti1801 (Mensaje 548957)
Código Delphi [-]
ADOQuery1Item: TAutoIncField;

Es autonumerico pero lo que debo hacer es solo leerlo pero entonces el problema puede ser que venga de aqui ya que es este punto yo le estoy pasando el valor ITEM para luego leerlo
Código Delphi [-]
Label3.Caption := ADOQuery1.fieldbyname('MINIMO').asstring;
[/delphi]
ADOQueryUpdate.SQL.Add( 'WHERE Item =:Item,');
ADOQueryUpdate.Parameters.ParamByName('Item').Value := StrToInt(Label3.Caption);
[/delphi]

Ya vi donde esta el problema pero si voy a necesitar ayuda

Código Delphi [-]
procedure TFormCaja.SpeedButton1Click(Sender: TObject);
begin
    With ADOQuery1 do
        begin
        Close;
        Open;
        ADOQuery1.First;
         begin
         Label1.Caption := 'A00' + ADOQuery1.fieldbyname('MINIMO').asstring;
         Label3.Caption := ADOQuery1.fieldbyname('MINIMO').asstring;
         Image3.Visible := true;
         begin
         With ADOQueryUpdate do
         Close;
         Open;
        ADOQueryUpdate.SQL.Add( 'UPDATE Tiket');
        ADOQueryUpdate.SQL.Add( 'SET');
        ADOQueryUpdate.SQL.Add( 'Estatus =:Estatus,');
        ADOQueryUpdate.SQL.Add( 'Usuario  =:Usuario,');
        ADOQueryUpdate.SQL.Add( 'WHERE Item =:Item,');
        //Asignación de valores a los parametros...
        //Precaución con los tipos de datos
        ADOQueryUpdate.Parameters.ParamByName('Item').Value := StrToInt(Label3.Caption);
        ADOQueryUpdate.Parameters.ParamByName('Estatus').Value :='OLD';
        ADOQueryUpdate.Parameters.ParamByName('Usuario').Value := Label4.caption;
        ADOQueryUpdate.ExecSQL;
        //ADOQueryUpdate.SQL.Clear;
        //ADOQueryUpdate.SQL.Add( 'UPDATE Tiket SET');
        //ADOQueryUpdate.SQL.Add( 'Estatus = ' +QuotedStr('OLD'));
        //ADOQueryUpdate.SQL.Add(' WHERE Item =:valor');
        //ADOQueryUpdate.Parameters.ParamByName('Valor').Value := StrToInt(Label3.Caption);
        //ADOQueryUpdate.ExecSQL;
        end;


      end;
end;


Resulta que me esta dando error porque como es el primer procedimiento aun el Label3.caption esta vacio por ellos me da este error debo colocar un IF pero no se donde poderlo colocar para que me funciones, es decir si el laber3.caption esta vacio que solamente corra la primera instrucion

Código Delphi [-]
procedure TFormCaja.SpeedButton1Click(Sender: TObject);
begin
    With ADOQuery1 do
        begin
        Close;
        Open;
        ADOQuery1.First;
         begin
         Label1.Caption := 'A00' + ADOQuery1.fieldbyname('MINIMO').asstring;
         Label3.Caption := ADOQuery1.fieldbyname('MINIMO').asstring;
         Image3.Visible := true;
         begin


de lo contrario que la recorra toda:

Código Delphi [-]
procedure TFormCaja.SpeedButton1Click(Sender: TObject);
begin
    With ADOQuery1 do
        begin
        Close;
        Open;
        ADOQuery1.First;
         begin
         Label1.Caption := 'A00' + ADOQuery1.fieldbyname('MINIMO').asstring;
         Label3.Caption := ADOQuery1.fieldbyname('MINIMO').asstring;
         Image3.Visible := true;
         begin
         With ADOQueryUpdate do
         Close;
         Open;
        ADOQueryUpdate.SQL.Add( 'UPDATE Tiket');
        ADOQueryUpdate.SQL.Add( 'SET');
        ADOQueryUpdate.SQL.Add( 'Estatus =:Estatus,');
        ADOQueryUpdate.SQL.Add( 'Usuario  =:Usuario,');
        ADOQueryUpdate.SQL.Add( 'WHERE Item =:Item,');
        //Asignación de valores a los parametros...
        //Precaución con los tipos de datos
        ADOQueryUpdate.Parameters.ParamByName('Item').Value := StrToInt(Label3.Caption);
        ADOQueryUpdate.Parameters.ParamByName('Estatus').Value :='OLD';
        ADOQueryUpdate.Parameters.ParamByName('Usuario').Value := Label4.caption;
        ADOQueryUpdate.ExecSQL;
        //ADOQueryUpdate.SQL.Clear;
        //ADOQueryUpdate.SQL.Add( 'UPDATE Tiket SET');
        //ADOQueryUpdate.SQL.Add( 'Estatus = ' +QuotedStr('OLD'));
        //ADOQueryUpdate.SQL.Add(' WHERE Item =:valor');
        //ADOQueryUpdate.Parameters.ParamByName('Valor').Value := StrToInt(Label3.Caption);
        //ADOQueryUpdate.ExecSQL;
        end;

duilioisola 04-11-2022 09:14:12

Aquí te sobran comas:

Código Delphi [-]
        ADOQueryUpdate.SQL.Add( 'UPDATE Tiket');
        ADOQueryUpdate.SQL.Add( 'SET');
        ADOQueryUpdate.SQL.Add( 'Estatus =:Estatus,');
        ADOQueryUpdate.SQL.Add( 'Usuario  =:Usuario,');
        ADOQueryUpdate.SQL.Add( 'WHERE Item =:Item,');

Código SQL [-]
UPDATE Tiket
SET
Estatus =:Estatus,
Usuario  =:Usuario,  //<-- esta coma está de mas. Implica que hay otro campo para actualizar
WHERE Item =:Item,   //<-- esta coma está de mas. Esta condición es lógica, del tipo "(item=:item) and (estatus='OLD')"

Casimiro Notevi 04-11-2022 09:51:56

Cita:

Empezado por giantonti1801 (Mensaje 548928)
...

Creo que ya es momento de que le eches un vistazo a nuestra guía de estilo, gracias.


La franja horaria es GMT +2. Ahora son las 01:21:33.

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