Hace tiempo no escribía nada, hoy revisando los foros me encontré que siempre existe ese gran problema de manejar procedimientos almacenados desde .NET… humm en realidad no es un gran problema, es muy simple y es por esto mismo que hice estos códigos de ejemplo, para que vean como pueden hacerlo. Espero les sirva a quienes recién se inician.
1. Ejecutando un Simple Procedimiento Almacenado
Para esto antes que nada debemos tener un SP (Stored Procedure) creado
CREATE PROCEDURE spEjecutar
AS
BEGIN
/* Mi Codigo */
END
GO
Para llamar o ejecutar este SP en .NET solo necesitamos el siguiente código:
Dim objCommand As New SqlClient.SqlCommand("spEjecutar"), _
Conexion As String = "server='SERVIDOR'; user id='usuario'; password='miclave'; database='MiBaseDatos'"
objCommand.CommandType = CommandType.StoredProcedure
objCommand.Connection = New SqlClient.SqlConnection(Conexion)
objCommand.Connection.Open()
objCommand.ExecuteNonQuery()
objCommand.Connection.Close()
Ups… pero esté ejemplo es muy simple… veamos uno con parámetros y con devolución de datos.
2. Ejecutando un SP con parámetros que devuelva un conjunto de datos
Aquí tenemos dos opciones, dejar este conjunto de datos en un objeto SqlDataReader o un SqlDataAdapter, la diferencia principalmente es que SqlDataReader es que solo se puede leer hacia adelante y está conectada con la base de datos, en cambio SqlDataAdapter sirve para intercambiar datos entre la Base de Datos y un conjunto de datos (DataSet o DataTable)
Antes que nada creemos un Procedimiento Almacenado que reciba un parámetro y devuelva un conjunto de datos.
CREATE PROCEDURE spEjecutar
@Codigo VARCHAR(10)
AS
BEGIN
SELECT Codigo, Nombre
FROM Tabla
WHERE Codigo = @Codigo
END
GO
Para llamar este SP desde .NET a un SqlDataReader
Dim objCommand As New SqlClient.SqlCommand("spEjecutar"), _
Conexion As String = "server='SERVIDOR'; user id='usuario'; password='miclave'; database='MiBaseDatos'"
objCommand.CommandType = CommandType.StoredProcedure
objCommand.Parameters.Add("@Codigo", SqlDbType.VarChar, 10)
objCommand.Parameters("@Codigo").Value = "Mi Código"
objCommand.Connection = New SqlClient.SqlConnection(Conexion)
objCommand.Connection.Open()
Dim objReader As SqlDataReader = objCommand.ExecuteReader()
While objReader.Read()
Response.Write(objReader.Item("Codigo").ToString() & "-" & _
objReader.Item("Nombre").ToString() & "<br>")
End While
objReader.Close()
objCommand.Connection.Close()
Para llamar este SP desde .NET a un SqlDataAdapter a un DataSet
Dim objCommand As New SqlClient.SqlCommand("spEjecutar"), _
Conexion As String = "server='SERVIDOR'; user id='usuario'; password='miclave'; database='MiBaseDatos'"
objCommand.CommandType = CommandType.StoredProcedure
objCommand.Parameters.Add("@Codigo", SqlDbType.VarChar, 10)
objCommand.Parameters("@Codigo").Value = "Mi Código"
objCommand.Connection = New SqlClient.SqlConnection(Conexion)
objCommand.Connection.Open()
Dim objAdapter As New SqlDataAdapter(objCommand), _
objDataSet As New DataSet
objAdapter.Fill(objDataSet, "Tabla")
objCommand.Connection.Close()
Dim objRow As DataRow
For Each objRow In objDataSet.Tables("Tabla").Rows
Response.Write(objRow.Item("Codigo").ToString() & "-" & _
objRow.Item("Nombre").ToString() & "<br>")
Next
Para llamar este SP desde .NET a un SqlDataAdapter a un DataTable
Dim objCommand As New SqlClient.SqlCommand("spEjecutar"), _
Conexion As String = "server='SERVIDOR'; user id='usuario'; password='miclave'; database='MiBaseDatos'"
objCommand.CommandType = CommandType.StoredProcedure
objCommand.Parameters.Add("@Codigo", SqlDbType.VarChar, 10)
objCommand.Parameters("@Codigo").Value = "Mi Código"
objCommand.Connection = New SqlClient.SqlConnection(Conexion)
objCommand.Connection.Open()
Dim objAdapter As New SqlDataAdapter(objCommand), _
objDataTable As New DataTable
objAdapter.Fill(objDataTable)
objCommand.Connection.Close()
Dim objRow As DataRow
For Each objRow In objDataTable.Rows
Response.Write(objRow.Item("Codigo").ToString() & "-" & _
objRow.Item("Nombre").ToString() & "<br>")
Next
3. Ejecutando un SP con parámetros que devuelva un parámetro de Salida.
Para este caso tenemos el siguiente Procedimiento Almacenado con 2 parámetros uno de entrada y otro de salida.
CREATE PROCEDURE spEjecutar
@Codigo VARCHAR(10),
@Nombre VARCHAR(100) OUT
AS
BEGIN
SELECT @Nombre = Nombre
FROM Tabla
WHERE Codigo = @Codigo
END
GO
Para llamar este SP y obtener el resultado en el parámetro de salida desde .NET se debe realizar lo siguiente:
Dim objCommand As New SqlClient.SqlCommand("spEjecutar"), _
Conexion As String = "server='SERVIDOR'; user id='usuario'; password='miclave'; database='MiBaseDatos'"
objCommand.CommandType = CommandType.StoredProcedure
objCommand.Parameters.Add("@Codigo", SqlDbType.VarChar, 10)
objCommand.Parameters("@Codigo").Value = "Mi Código"
objCommand.Parameters.Add("@Nombre", SqlDbType.VarChar, 100)
objCommand.Parameters("@Nombre").Direction = ParameterDirection.Output
objCommand.Connection = New SqlClient.SqlConnection(Conexion)
objCommand.Connection.Open()
objCommand.ExecuteScalar()
Response.Write("El Nombre es: " & objCommand.Parameters("@Nombre").Value)
objCommand.Connection.Close()
Espero les sea de utilidad, no es tan complejo… pero estoy seguro que será de ayuda para los novatos o no tan novatos.
Saludos,
Jhonny Vargas
Santiago de Chile
Hummm...
El otro día jugando con un Cubo Rubik me quise tomar el tiempo de cuanto me demoraba, para esto solía usar el cronómetro del celular... jejeje... pero en un momento quise tener uno en mi portatil... encontré en internet unos instaladores, pero me propuse hacer uno yo mismo... jejeje nada del otro mundo.
Lo primero fue como sumar y restar Horas... para eso encontré el tipo de datos TimeSpan que me sirvió notablemente para esto.
Puedes descargar el ejemplo completo desde aqui --->> Download CLAVE ZIP: msmvps.com/jvargas
Para comenzar cree un formulario windows con un label, dos botones y un control timer.
El formulario es el siguiente:

El label se llama lblTiempo, el boton ">" se llama btnIniciarPausar, el botón "O" se llama btnDetener y el timer se llama tmrTiempo.
Ahi les adjunto los eventos correspondientes..
Dim FechaInicio As DateTime, _
TiempoActivo As TimeSpan
Private Sub btnIniciarPausar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnIniciarPausar.Click
If btnIniciarPausar.Text = "||" Then
'PAUSA
btnIniciarPausar.Text = ">"
tmrTiempo.Stop()
Else
'REINICIAR
Dim FechaActiva As DateTime
FechaActiva = lblTiempo.Text
TiempoActivo = FechaActiva.TimeOfDay
FechaInicio = Now
btnDetener.Enabled = True
btnIniciarPausar.Text = "||"
tmrTiempo.Start()
End If
End Sub
Private Sub btnDetener_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDetener.Click
btnDetener.Enabled = False
btnIniciarPausar.Text = ">"
lblTiempo.Text = "00:00:00.000"
tmrTiempo.Stop()
End Sub
Private Sub tmrTiempo_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tmrTiempo.Tick
Dim Tiempo As TimeSpan
Tiempo = Now.Subtract(FechaInicio).Duration
Tiempo += TiempoActivo
lblTiempo.Text = Microsoft.VisualBasic.Right("00" & Tiempo.Hours, 2) & ":" & _
Microsoft.VisualBasic.Right("00" & Tiempo.Minutes, 2) & ":" & _
Microsoft.VisualBasic.Right("00" & Tiempo.Seconds, 2) & "." & _
Microsoft.VisualBasic.Right("000" & Tiempo.Milliseconds, 3)
Me.Refresh()
End Sub
Espero les sirva este ejemplo en el uso de TimeSpan al igual que Datetime.
Saludos,
Jhonny Vargas P.
Gracias Gerardo.... adjunto el código para C#, por si algún otro usuario lo llegara a necesitar.
Para VB.NET http://msmvps.com/blogs/jvargas/pages/convertirnumeroletras.aspx
Gracias por tu aporte.
:)
using System;
using System.Collections.Generic;
using System.Text;
namespace Conversiones
{
class Conv
{
public string enletras(string num)
{
string res, dec = "";
Int64 entero;
int decimales;
double nro;
try
{
nro = Convert.ToDouble(num);
}
catch
{
return "";
}
entero = Convert.ToInt64(Math.Truncate(nro));
decimales = Convert.ToInt32(Math.Round((nro - entero) * 100, 2));
if (decimales > 0)
{
dec = " CON " + decimales.ToString() + "/100";
}
res = toText(Convert.ToDouble(entero)) + dec;
return res;
}
private string toText(double value)
{
string Num2Text = "";
value = Math.Truncate(value);
if (value == 0) Num2Text = "CERO";
else if (value == 1) Num2Text = "UNO";
else if (value == 2) Num2Text = "DOS";
else if (value == 3) Num2Text = "TRES";
else if (value == 4) Num2Text = "CUATRO";
else if (value == 5) Num2Text = "CINCO";
else if (value == 6) Num2Text = "SEIS";
else if (value == 7) Num2Text = "SIETE";
else if (value == 8) Num2Text = "OCHO";
else if (value == 9) Num2Text = "NUEVE";
else if (value == 10) Num2Text = "DIEZ";
else if (value == 11) Num2Text = "ONCE";
else if (value == 12) Num2Text = "DOCE";
else if (value == 13) Num2Text = "TRECE";
else if (value == 14) Num2Text = "CATORCE";
else if (value == 15) Num2Text = "QUINCE";
else if (value < 20) Num2Text = "DIECI" + toText(value - 10);
else if (value == 20) Num2Text = "VEINTE";
else if (value < 30) Num2Text = "VEINTI" + toText(value - 20);
else if (value == 30) Num2Text = "TREINTA";
else if (value == 40) Num2Text = "CUARENTA";
else if (value == 50) Num2Text = "CINCUENTA";
else if (value == 60) Num2Text = "SESENTA";
else if (value == 70) Num2Text = "SETENTA";
else if (value == 80) Num2Text = "OCHENTA";
else if (value == 90) Num2Text = "NOVENTA";
else if (value < 100) Num2Text = toText(Math.Truncate(value / 10) * 10) + " Y " + toText(value % 10);
else if (value == 100) Num2Text = "CIEN";
else if (value < 200) Num2Text = "CIENTO " + toText(value - 100);
else if ((value == 200) || (value == 300) || (value == 400) || (value == 600) || (value == 800)) Num2Text = toText(Math.Truncate(value / 100)) + "CIENTOS";
else if (value == 500) Num2Text = "QUINIENTOS";
else if (value == 700) Num2Text = "SETECIENTOS";
else if (value == 900) Num2Text = "NOVECIENTOS";
else if (value < 1000) Num2Text = toText(Math.Truncate(value / 100) * 100) + " " + toText(value % 100);
else if (value == 1000) Num2Text = "MIL";
else if (value < 2000) Num2Text = "MIL " + toText(value % 1000);
else if (value < 1000000)
{
Num2Text = toText(Math.Truncate(value / 1000)) + " MIL";
if ((value % 1000) > 0) Num2Text = Num2Text + " " + toText(value % 1000);
}
else if (value == 1000000) Num2Text = "UN MILLON";
else if (value < 2000000) Num2Text = "UN MILLON " + toText(value % 1000000);
else if (value < 1000000000000)
{
Num2Text = toText(Math.Truncate(value / 1000000)) + " MILLONES ";
if ((value - Math.Truncate(value / 1000000) * 1000000) > 0) Num2Text = Num2Text + " " + toText(value - Math.Truncate(value / 1000000) * 1000000);
}
else if (value == 1000000000000) Num2Text = "UN BILLON";
else if (value < 2000000000000) Num2Text = "UN BILLON " + toText(value - Math.Truncate(value / 1000000000000) * 1000000000000);
else
{
Num2Text = toText(Math.Truncate(value / 1000000000000)) + " BILLONES";
if ((value - Math.Truncate(value / 1000000000000) * 1000000000000) > 0) Num2Text = Num2Text + " " + toText(value - Math.Truncate(value / 1000000000000) * 1000000000000);
}
return Num2Text;
}
}
}