function printExpensiveItems(maxPrice Price in)
tempItem Item;
open expensiveItems for tempItem with
#sql{
select
EGL.ITEM.ITEM_ID, EGL.ITEM.NAME, EGL.ITEM.IMAGE,
EGL.ITEM.PRICE, EGL.ITEM.DESCRIPTION
from EGL.ITEM
where
EGL.ITEM.PRICE >= :maxPrice
order by
EGL.ITEM.ITEM_ID asc
};
forEach (tempItem)
SysLib.writeStdout(tempItem.Name :: " " ::
tempItem.Description :: " $" :: tempItem.Price);
end
Pero ¿qué debe hacer si desea que se devuelvan los artículos cuyo
precio es igual o
inferior al del parámetro? O bien, ¿qué debe hacer si desea que se devuelvan los
artículos cuyo precio se sitúa entre un precio máximo y un precio mínimo? Utilizando el
código SQL explícito de la sentencia open, tendría que
codificar tres funciones, una para cada una de las posibilidades, ya que las comparaciones
de la cláusula WHERE de la sentencia SQL se codifican manualmente. selectStatement STRING = "select * from EGL.ITEM where EGL.ITEM.PRICE >= 500";A continuación, se utiliza la sentencia prepare para convertir la serie en una sentencia SQL. También debe especificar un nombre para la sentencia y, opcionalmente, una variable de registro para indicar el componente SQLRecord sobre el que operará la sentencia:
tempItem Item; prepare preparedStatement from selectStatement for tempItem;A continuación, puede utilizar la sentencia preparada en lugar de SQL explícito en una sentencia EGL get, open o execute (aprenderá más acerca de la sentencia execute en una lección posterior):
open expensiveItems for tempItem with preparedStatement;
tempItem Item; maxPrice Price = 500; selectStatement STRING = "select * from EGL.ITEM where EGL.ITEM.PRICE >= :maxPrice"; prepare preparedStatement from selectStatement for tempItem;En este caso, la sentencia SQL real incluirá la serie :maxPrice exactamente tal como está, sin utilizarla como variable de lenguaje principal y sustituirla por el valor de la variable maxPrice. El resultado será una sentencia SQL incorrecta.
tempItem Item; maxPrice Price = 500; selectStatement STRING = "select * from EGL.ITEM where EGL.ITEM.PRICE >= " :: maxPrice; prepare preparedStatement from selectStatement for tempItem;En este caso, el valor de la variable maxPrice se resuelve cuando EGL crea la serie, creando la siguiente sentencia SQL:
select * from EGL.ITEM where EGL.ITEM.PRICE >= 500Más adelante en esta lección aprenderá un procedimiento alternativo de utilizar variables en sentencias preparadas.
incorrectSQL STRING; incorrectSQL = "select * from EGL.ITEM where"; incorrectSQL ::= "EGL.ITEM.PRICE >= :maxPrice"; incorrectSQL ::= "order by EGL.ITEM.PRICE";Este ejemplo crea la siguiente sentencia SQL incorrecta:
select * from EGL.ITEM whereEGL.ITEM.PRICE >= :maxPriceorder by EGL.ITEM.PRICEEsta sentencia necesita un espacio después de WHERE y otro antes de ORDER BY.
Asimismo, las sentencias SQL preparadas, como el SQL explícito, deben ser apropiadas para la sentencia EGL con la que van a utilizarse. Por ejemplo, las sentencias EGL get y open esperan un conjunto de resultados. Para utilizar una sentencia preparada con cualquiera de estas sentencias, el código SQL debe devolver un conjunto de resultados. Por ello, no puede prepararse una sentencia SQL INSERT o DELETE y luego utilizarla con get u open.
Consulta completa: select * from EGL.ITEM where EGL.ITEM.PRICE between 50.00 and 500.00 order by EGL.ITEM.PRICE Serial Mouse Great little mouse. All kinds'a applications. $65.22 Keyboard Got QWERTY? If not, go get this awesome flat keyboard. $78.99 Watch Keep time - and look rakish! $99.01 Shredder Don't let that politically-sensitive document fall into the wrong hands! $198.99 Combination Safe Keep your valuables safe and secure. Put 'em in here. $222.22Puede editar los valores de parámetro y probar rangos diferentes, incluidos valores nulos, como en este ejemplo:
function main()
minPrice, maxPrice Price?;
minPrice = 500;
maxPrice = null;
try
printItemRange(minPrice, maxPrice);
onException(exception SQLException)
handleDBException(exception);
end
end
Si se pasan valores de 500 y nulo, se generan resultados como estos: Consulta completa: select * from EGL.ITEM where EGL.ITEM.PRICE >= 500.00 order by EGL.ITEM.PRICE Desktop PC Lots'a power, at the right price. Includes monitor. $888.55 Laptop PC Great little machine. Take it anywhere with you. $1111.11
Este es el código completo del archivo selectItems.egl. Si ve errores marcados con símbolos X rojos en el archivo, asegúrese de que el código coincide con el código de este archivo: Archivo selectItems.egl completado después de la lección 4A.
selectStatement STRING = "select * from EGL.ITEM where "; ... selectStatement ::= "EGL.ITEM.PRICE between " :: minPrice :: " and " :: maxPrice :: " ";Al crear una sentencia preparada, también puede situar signos de interrogación (?) en la sentencia, indicando que los valores se especificarán más adelante:
selectStatement2 STRING = "select * from EGL.ITEM where " :: "EGL.ITEM.PRICE between ? and ? " :: "order by EGL.ITEM.PRICE"; tempItem Item; prepare preparedStatement2 from selectStatement2 for tempItem;Ahora, la sentencia preparada tiene lugar para dos variables de lenguaje principal, representadas por los signos de interrogación de la cláusula BETWEEN. Cuando esté preparado para utilizar la sentencia preparada, inserte los valores con la sentencia using. Por ejemplo, para buscar las filas cuyo precio esté entre 5 y 500, pase los literales 5 y 500 a la sentencia:
open expensiveItems2 for tempItem with preparedStatement2 using 5, 500;Evidentemente, también puede utilizar variables junto con la palabra clave using:
open expensiveItems2 for tempItem with preparedStatement2 using minPrice, maxPrice;
function printRanges()
tempItem Item;
selectStatement string = "select * from EGL.ITEM where " ::
"EGL.ITEM.PRICE between ? and ? " ::
"order by EGL.ITEM.PRICE";
prepare preparedStatement from selectStatement for tempItem;
SysLib.writeStdout("\nVisualizando valores entre 0 y 200");
open expensiveItems for tempItem with preparedStatement using 0, 200;
forEach(tempItem)
SysLib.writeStdout(tempItem.Name :: " " :: tempItem.Description ::
" $" :: tempItem.Price);
end
SysLib.writeStdout("\nVisualizando valores entre 200 y 500");
open expensiveItems for tempItem with preparedStatement using 200, 500;
forEach(tempItem)
SysLib.writeStdout(tempItem.Name :: " " :: tempItem.Description ::
" $" :: tempItem.Price);
end
SysLib.writeStdout("\nVisualizando valores entre 500 y 1.000");
open expensiveItems for tempItem with preparedStatement
using 500, 1000;
forEach(tempItem)
SysLib.writeStdout(tempItem.Name :: " " :: tempItem.Description ::
" $" :: tempItem.Price);
end
end
Utilizando variables de lenguaje principal de ese modo, es posible reescribir el programa de la sección anterior para que utilice una sola sentencia preparada, en lugar de modificar la sentencia para cada posible caso: