Funciones
Función | Descripción |
---|---|
sqlTipo | Analiza el tipo de dato del valor de entrada y retorna NULL, NUMBER, DATE o STRING |
sqlLiteral | Convierte un valor literal de MS-Access en un literal de SQL. Opcionalmente se puede forzar el tipo de datos indicando cual es. |
sqlParametrizar | Reemplaza todos los parámetros de SQL por los valores proporcionados sin tener en cuenta el tipo |
sqlParametrizarLiterales | Reemplaza todos los parámetros de SQL por los valores teniendo en cuenta el tipo |
Ejemplos
Los parámetros se sustituyen siguiendo el orden en el que aparecen en el SQL
-
sqlParametrizarLiterales(
"insert into tabla(campo1, campo2, campo3) select «valor1», «valor2», «valor3»"
, Date(), "Pepe", 1000)insert into tabla(campo1, campo2, campo3) select #4/11/2009#, 'Pepe', 1000
-
sqlParametrizar(
"select id, «campo» from «tabla» order by «campo»"
, "usuario", "usuarios")select id, usuario from usuarios order by usuario
-
sqlParametrizar(
"update tabla set titulo=«campo», referencia=«referencia»"
, sqlLiteral(123, "STRING"), sqlLiteral(Date(), "DATE"))update tabla set titulo='123', referencia=#4/11/2009#
Código fuente
Option Compare Database
Option Explicit
'================================================
' Módulo SQL
' 2009-IV-11 <fco@proinf.net>
'================================================
'------------------------------------------------
' Tipos de datos
'------------------------------------------------
Public Function sqlTipo(ByVal valor As Variant) As String
'Obtiene el tipo de datos SQL
'Ej: sqlTipo(123) --> "NUMBER"
'2009-I-30
If Nz(valor, "") = "" Then
sqlTipo = "NULL"
ElseIf IsNumeric(valor) Then
sqlTipo = "NUMBER"
ElseIf IsDate(valor) Then
sqlTipo = "DATE"
Else
sqlTipo = "STRING"
End If
End Function
Public Function sqlLiteral( _
ByVal valor As Variant, _
Optional ByVal tipo As String = "AUTO" _
) As String
'Convierte un variant en un literal SQL
'Ej: sqlLiteral("Pepe's") --> 'Pepe''s'
'2009-I-25, 2009-I-30 <fco@proinf.net>
Const COMA = ","
Const PUNTO = "."
Const COMILLA = "'"
If Nz(valor, "") = "" Then
tipo = "NULL"
ElseIf tipo = "AUTO" Then
tipo = sqlTipo(valor)
End If
Select Case tipo
Case "NULL":
sqlLiteral = ""
Case "NUMBER": 'Cambiar la coma por punto para que coincida con el sistema estadounidense
sqlLiteral = Replace(Nz(valor, 0), COMA, PUNTO)
Case "DATE": 'Poner el formato de fecha al estilo estadounidense
sqlLiteral = Format(CDate(valor), "\#mm/dd/yyyy\#")
Case "STRING": 'Duplicar las COMILLA simples
sqlLiteral = COMILLA & Replace(valor, COMILLA, COMILLA & COMILLA) & COMILLA
End Select
End Function
'------------------------------------------------
' Parámetros SQL
'------------------------------------------------
Public Function sqlParametrizar(ByVal sql As String, ParamArray parametros()) As String
'Parametriza el SQL sin tener en cuenta si se trata o no de literales SQL
'Ej: sqlParametrizar("select id, <campo> from <tabla> order by <campo>", "usuario", "usuarios")
' --> "select id, usuario from usuarios order by usuario"
'2009-I-26
Dim elemento As Variant
Dim parametro As String
For Each elemento In parametros
parametro = ObtenerPrimerParametro(sql)
If parametro = "" Then
Exit For
Else
sql = Replace(sql, parametro, elemento)
End If
Next
sqlParametrizar = sql
End Function
Public Function sqlParametrizarLiterales(ByVal sql As String, ParamArray parametros()) As String
'Parametriza los literales SQL: si es un texto lo entrecomilla, si es una fecha le pone #, etc.
'Ej: ParametrizarLiteralesSQL("insert into tabla(campo1, campo2, campo3) select «valor1», «valor2», «valor3»", date, "pepe", 1001)
' --> "insert into tabla(campo1, campo2, campo3) select #2009/4/11#, 'pepe', 1001)
'2009-I-25
Dim elemento As Variant
Dim parametro As String
For Each elemento In parametros
parametro = ObtenerPrimerParametro(sql)
If parametro = "" Then
Exit For
Else
sql = Replace(sql, parametro, sqlLiteral(elemento))
End If
Next
sqlParametrizarLiterales = sql
End Function
Private Function ObtenerPrimerParametro(ByVal sql As String) As String
Dim pos1 As Integer: pos1 = InStr(sql, "«")
Dim pos2 As Integer: pos2 = InStr(sql, "»")
If pos1 > 0 Or pos2 > 0 Then ObtenerPrimerParametro = Mid(sql, pos1, pos2 - pos1 + 1)
End Function
'------------------------------------------------
' Ejecución
'------------------------------------------------
Public Function sqlEjecutar(ByVal sql As String) As Boolean
'2009-IV-10 <fco@proinf.net>
On Error GoTo Errores
CurrentDb.Execute sql, dbFailOnError
sqlEjecutar = True
Salida:
Exit Function
Errores:
MsgBox "Error", vbExclamation, Err.Description
Resume Salida
End Function