Procedimiento almacenado SQLServer / SQLServer Stored Procedure

408 views
Skip to first unread message

danr...@gmail.com

unread,
Jan 1, 2025, 9:37:25 PM1/1/25
to oo...@googlegroups.com, harbou...@googlegroups.com

Hola,

Yo utilizo el objeto ADODB.Recordset para recorrer tablas SQL SERVER desde harbour

Ahora tengo que ejecutar un procedimiento almacenado y recorrer los registros que retorna.

¿Cómo se hace?

Muchas gracias

Daniel

La Reja Buenos Aires

 

Hi,

I use the ADODB.Recordset object to go through SQL SERVER tables from Harbour

Now I have to execute a stored procedure and go through the records it returns.

How do I do it?

Thanks

Daniel

La Reja Buenos Aires

 

cod...@outlook.com

unread,
Jan 2, 2025, 3:51:43 AM1/2/25
to Harbour Users

danr...@gmail.com

unread,
Jan 2, 2025, 6:45:10 AM1/2/25
to harbou...@googlegroups.com

Hola,

Pude ejecutar el procedimiento almacenado (eso creo), con el siguiente código

 

oConn := CreateObject("ADODB.Connection")
oConn:ConnectionString := "PROVIDER=SQLOLEDB;DATASOURCE=myserver;DATABASE=mydbname;UID=myuser;PWD=mypassword"
oConn:Open()
oConn:Execute("sp_copiar_diagrama '"+Str(nCodDes,3)+"', '"+Str(nCodHas,3)+"' ")
oConn:Close()

 

 

pero tengo que recorrer los registros que retorna y utilizando oConn como si fuese un ADODB.Recordset, no me deja

muchas gracias

***************************************************************************************************************************************************

Hello,

I was able to execute the stored procedure (I think), with the following code

 

oConn := CreateObject("ADODB.Connection")

oConn:ConnectionString := "PROVIDER=SQLOLEDB;DATASOURCE=myserver;DATABASE=mydbname;UID=myuser;PWD=mypassword"

oConn:Open()

oConn:Execute("sp_copiar_diagrama '"+Str(nCodDes,3)+"', '"+Str(nCodHas,3)+"' ")

oConn:Close()

 

but I have to go through the records that it returns and using oConn as if it were an ADODB.Recordset, it doesn't let me

thanks a lot

--
You received this message because you are subscribed to the Google Groups "Harbour Users" group.
Unsubscribe: harbour-user...@googlegroups.com
Web: https://groups.google.com/group/harbour-users
---
You received this message because you are subscribed to the Google Groups "Harbour Users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to harbour-user...@googlegroups.com.
To view this discussion visit https://groups.google.com/d/msgid/harbour-users/6ef9d559-e67c-46a0-8a00-f4286600c494n%40googlegroups.com.

cod...@outlook.com

unread,
Jan 2, 2025, 7:28:14 AM1/2/25
to Harbour Users
Hi.

According to this message


may be you can do this

rs = oConn:Execute("sp_copiar_diagrama '"+Str(nCodDes,3)+"', '"+Str(nCodHas,3)+"' ")

I have used ADODB from Harbour but not with stored procedures. I was reading and updating .MDB files with no problem. 

Regards,
Simo.

Lautaro Moreira

unread,
Jan 2, 2025, 7:35:35 AM1/2/25
to harbou...@googlegroups.com, danr...@gmail.com

Estimado,

el retorno de oConn:Execute( ... ) de la llamada al procedimiento almacenado deberia ser un recordset que puedes recorrer , si es que el procedimiento almacendo devuelve un conjunto de registros.

Asi que tu codigo deberia quedar asi : orecordset := oConn:Execute(....) luego usas orecordset como habitualmente lo haces ( ojo es un recordset de solo lectura por lo que no podras hacer modificaciones en el )

Atte.,

Lautaro Moreira

danr...@gmail.com

unread,
Jan 2, 2025, 7:57:15 AM1/2/25
to harbou...@googlegroups.com

Hola,

Cuando intento recorrer el recorset me da el siguiente error

 

WINOLE/1007  La operación no está permitida si el objeto está cerrado. (0x800A0E78): ADODB.Recordset

 

 

El código es:

 

rs:=win_oleCreateObject( "ADODB.Recordset" )

oConn := CreateObject("ADODB.Connection")

oConn:ConnectionString := "Provider=sqloledb;Data Source=10.200.0.46;Initial Catalog=Gecros;User Id=xxxxxx;Password=xxxxxxx;"

oConn:Open()

rs:=oConn:Execute("pa_getCompDeuda 1071088,1")

 

rs:MoveFirst() // el error sucede aquí

DO WHILE ! rs:EOF() // Procesar los registros retornados

    //? "Columna1: ", oRS:Fields( "Columna1" ):Value

    //? "Columna2: ", oRS:Fields( "Columna2" ):Value // Agrega más columnas según sea necesario

    rs:MoveNext()

ENDDO // Cerrar el Recordset oRS:Close()

 

 

oConn:Close()

 

Gracias

 

De: harbou...@googlegroups.com <harbou...@googlegroups.com> En nombre de cod...@outlook.com


Enviado el: jueves, 2 de enero de 2025 09:28
Para: Harbour Users <harbou...@googlegroups.com>

--

You received this message because you are subscribed to the Google Groups "Harbour Users" group.
Unsubscribe: harbour-user...@googlegroups.com
Web: https://groups.google.com/group/harbour-users
---
You received this message because you are subscribed to the Google Groups "Harbour Users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to harbour-user...@googlegroups.com.

José M. C. Quintas

unread,
Jan 2, 2025, 8:01:34 AM1/2/25
to harbou...@googlegroups.com

rs := oconn:Execute( "CALL theprocedure" )

rs := oconn:Execute( "CALL theprocedure()" )


José M. C. Quintas

Lautaro Moreira

unread,
Jan 2, 2025, 8:03:24 AM1/2/25
to harbou...@googlegroups.com, danr...@gmail.com

Hola,

Te falta rs:open()

En tu codigo quedaria :

...

rs:= oconn:execute(...)

rs:open()

...

Atte.,

Lautaro Moreira

danr...@gmail.com

unread,
Jan 2, 2025, 8:06:43 AM1/2/25
to Lautaro Moreira, harbou...@googlegroups.com

Gracias Lautaro,

Cuando intento usar la variable de retorno del execute, me da este error:

 

WINOLE/1007  La operación no está permitida si el objeto está cerrado. (0x800A0E78): ADODB.Recordset

 

No se a que se debe

Gracias

danr...@gmail.com

unread,
Jan 2, 2025, 9:56:56 AM1/2/25
to Lautaro Moreira, harbou...@googlegroups.com

Lautaro, le agregué el rs:open(), pero me sigue dando el mismo error

WINOLE/1007  La operación no está permitida si el objeto está cerrado. (0x800A0E78): ADODB.Recordset

En la línea siguiente:

 

DO WHILE !rs:EOF()

    rs:MoveNext()

ENDDO

oRS:Close()

 

oConn:Close()

 

Gracias

cod...@outlook.com

unread,
Jan 2, 2025, 10:23:46 AM1/2/25
to Harbour Users
Hi.

First I see that you have DO WHILE ! rs:EOF() and down you have oRS:Close(). Is it rs or oRS ?

If this is only typing error then try next.

Try not using stored procedure. Instead stored procedure write some SELECT sentence that will give you recordset, and then you will see will your slightly modified code work.
It is no need that recordset is same as one from stored procedure, just let it be any kind recordset. 
For example write 
oRS:=oConn:Execeute("SELECT * FROM table_name")

DO WHILE ! oRS:EOF()
    oRS:MoveNext()


ENDDO
oRS:Close()
oConn:Close()

Regards,

Simo.

david...@gmail.com

unread,
Jan 2, 2025, 3:18:50 PM1/2/25
to Harbour Users
Hi,

Your code should be:

oConn := CreateObject("ADODB.Connection")

oConn:ConnectionString := "Provider=sqloledb;Data Source=10.200.0.46;Initial Catalog=Gecros;User Id=xxxxxx;Password=xxxxxxx;"

oConn:Open()

rs:=oConn:Execute("CALL `pa_getCompDeuda`( 1071088,1)")

// you should treat it like any other function putting the parameters within the parenthesis.

// if your parameter is of type character or date it should go between single quotes just like any SQL statement

 // Using MySQL Note the character ` (don´t know what it is called) is not a ' single quote


rs:MoveFirst() // el error sucede aquí

DO WHILE ! rs:EOF() // Procesar los registros retornados

    //? "Columna1: ", oRS:Fields( "Columna1" ):Value

    //? "Columna2: ", oRS:Fields( "Columna2" ):Value // Agrega más columnas según sea necesario

    rs:MoveNext()

ENDDO // Cerrar el Recordset oRS:Close()


You do NOT need to OPEN the recordset.
You should Close it when done.

Hope this helps.

Regards,
David Field

José M. C. Quintas

unread,
Jan 2, 2025, 7:19:41 PM1/2/25
to harbou...@googlegroups.com

I use this for MySQL, inside my ADOClass:

METHOD ExecuteProcedureNoReturn( ... ) CLASS ADOClass

   LOCAL cSQL, aItem, aList := hb_AParams()

   cSQL := "CALL " + aList[ 1 ]
   hb_ADel( aList, 1, .T. )

   cSQL += "("
   FOR EACH aItem IN aList
      cSQL += ValueSQL( aItem )
      cSQL += iif( aItem:__ENumIsLast(), "", "," )
   NEXT
   cSQL += ")"

   RETURN ::ExecuteNoReturn( cSQL )

METHOD ExecuteProcedure( ... ) CLASS ADOClass

   LOCAL cSQL, aItem, aList := hb_AParams()

   cSQL := "CALL " + aList[ 1 ]
   hb_ADel( aList, 1, .T. )

   cSQL += "("
   FOR EACH aItem IN aList
      cSQL += ValueSQL( aItem )
      cSQL += iif( aItem:__ENumIsLast(), "", "," )
   NEXT
   cSQL += ")"
   ::Execute( cSQL )

   RETURN Nil


Note: cnSQL is my class, not a connection.


cnSQL:ExecuteProcedure( "myprocedure", 125, 1 )

DO WHILE ! cnSQL:Eof()

   cnSQL:MoveNext()

ENDDO


Note2: if a stored procedure does not return data, you do not have data.


José M. C. Quintas

danr...@gmail.com

unread,
Jan 3, 2025, 7:19:12 AM1/3/25
to harbou...@googlegroups.com

Hola David,

Me sigue dando error de sintaxis en rs:=oConn:Execute(…

Probé con ` y con ‘

Gracias

 

 

Hi David,

I keep getting a syntax error in rs:=oConn:Execute(…

I tried with ` and with ‘

Thanks

 

image002.png

david...@gmail.com

unread,
Jan 3, 2025, 11:21:23 AM1/3/25
to Harbour Users
Para mssql la instrucción es EXECUTE en lugar de CALL. 
Sin corchetes. 
Saludos 
David Field 

danr...@gmail.com

unread,
Jan 8, 2025, 9:41:22 PM1/8/25
to harbou...@googlegroups.com

Hola David,

 

Probé de la siguiente forma:

 

oConn := CreateObject("ADODB.Connection")

oConn:ConnectionString :="Provider=sqloledb;Data Source=x.x.x.x;Initial Catalog=Gecros;User Id=xxxxx;Password=xxxxx;"

oConn:Open()

rs:=oConn:Execute("EXECUTE pa_getCompDeuda 1071088,1")

rs:Open()

 

rs:MoveFirst() // el error sucede aquí

DO WHILE ! rs:EOF() // Procesar los registros retornados

    rs:MoveNext()

ENDDO

 

Me sigue dando error al intentar usar el recordset

 

Las consultas select me funcionan sin problemas, pero nunca utilicé resultados de procedimientos almacenados desde harbour

 

En la misma pc funciona bien con SQL Server Managment Studio

 

 

Gracias

Daniel Goldberg

La Reja

Buenos Aires

image001.png

jparada

unread,
Jan 9, 2025, 11:11:17 AM1/9/25
to Harbour Users
Pues creo que te estás liando, intenta algo así y cuentas...

cSQL := [ EXEC dbo.uspVentaAnualMesLinea ] + ;
              [ @desde = ] + convertDataToSQL(fechaIni) + [,] + ;  
              [ @hasta = ] + convertDataToSQL(fechaFin) + [,] + ;  
              [ @agentes = ] + convertDataToSQL(agente[3])

oRs := oConn:Execute( cSQL)

Saludos,
Javier

danr...@gmail.com

unread,
Jan 9, 2025, 2:08:39 PM1/9/25
to harbou...@googlegroups.com

Gracias Javier,

Hice los cambios según tu ej:

 

oConn := CreateObject("ADODB.Connection")

oConn:ConnectionString :="Provider=sqloledb;Data Source=x.x.x.x;Initial Catalog=Gecros;User Id=xxxx;Password=xxxxxx;"

oConn:Open()

rs:=oConn:Execute("EXEC pa_getCompDeuda @agecta=1071088,@entfac_id=1")

 

rs:MoveFirst() // el error sucede aquí

DO WHILE ! rs:EOF() // Procesar los registros retornados

    rs:MoveNext()

ENDDO

 

Me sigue dando error al intentar recorrer el recordset (el erro dice: la operación no está permitida si el objeto está cerrado)

La conexión con el procedimiento almacenado se establece bien, porque si pongo un parámetro con el nombre mal, me dice que el parámetro no existe

 

También probé agregando:

 

rs:Open() y tampoco

 

y definiendo antes:  

rs:=win_oleCreateObject( "ADODB.Recordset" ) y tampoco funcionó

 

El procedimiento almacenado se ejecuta pero no puedo recorrer los registros de respuesta como si lo puedo hacer con SQL Server Managment Studio

jparada

unread,
Jan 9, 2025, 2:41:13 PM1/9/25
to Harbour Users
Tu problema debe ser las comillas en los valores, creo ya te habían comentado eso, haz una prueba

toma la consulta tal cual la estás poniendo en el prg, e intenta ejecutar en tu sql studio

Saludos,
Javier

david...@gmail.com

unread,
Jan 9, 2025, 3:56:09 PM1/9/25
to Harbour Users
Daniel,

1. Comprueba que la conexión haya sido realizada correctamente.
2. NO uses OPEN en el resultado del ::Execute
3. Asegurate de que el usuario tenga permisos para acceder a la función
4. Asegurate de estar usando la base de datos correcta
5. Usa exactamente el mismo comando SQL que utilizaste en SQL Server Managment Studio
oRs := oConn:Execute("Execute pa_getCompDeuda 1071088,1")

Saludos,
David Field

danr...@gmail.com

unread,
Jan 10, 2025, 9:27:05 AM1/10/25
to harbou...@googlegroups.com

Hola David,

1*La conexión se realiza correctamente, de hecho si pongo mal un parámetro me dice el parámetro no existe

2*sin el open sigue dando el mismo error

3*El usuario tiene todos los permisos

4*es correcta, ya que los comandos select funcionan bien

5*Con la mismo comando sql que en SQL Mana… da el mismo error

 

 

Gracias

Reply all
Reply to author
Forward
0 new messages