Cómo usar la declaración IF de MySQL

En este tutorial, aprenderá cómo usar la declaración IF de MySQL para ejecutar un bloque de código SQL basado en una condición específica.

Tenga en cuenta que MySQL tiene una función IF() que es diferente de la IFdeclaración descrita en este tutorial.

El IFenunciado tiene tres formas: enunciado simple IF-THEN , IF-THEN-ELSEenunciado y IF-THEN-ELSEIF- ELSEenunciado.

IF-THENDeclaración simple de MySQL

La IF-THENdeclaración le permite ejecutar un conjunto de declaraciones SQL basadas en una condición específica. A continuación se ilustra la sintaxis de la IF-THENinstrucción:

IF condition THEN 
   statements;
END IF;

En esta sintaxis:

  • Primero, especifique una condición para ejecutar el código entre IF-THENy END IF. Si el conditionse evalúa como TRUE, las declaraciones entre IF-THENy END IFse ejecutarán. De lo contrario, el control se pasa a la siguiente instrucción que sigue al END IF.
  • En segundo lugar, especifique el código que se ejecutará si se conditionevalúa como TRUE.

Usaremos la customerstabla de la base de datos de muestra para la demostración:

Consulte el siguiente GetCustomerLevel()procedimiento almacenado.

DELIMITER $$

CREATE PROCEDURE GetCustomerLevel(
    IN  pCustomerNumber INT, 
    OUT pCustomerLevel  VARCHAR(20))
BEGIN
    DECLARE credit DECIMAL(10,2) DEFAULT 0;

    SELECT creditLimit 
    INTO credit
    FROM customers
    WHERE customerNumber = pCustomerNumber;

    IF credit > 50000 THEN
        SET pCustomerLevel = 'PLATINUM';
    END IF;
END$$

DELIMITER ;

El procedimiento almacenado GetCustomerLevel()acepta dos parámetros: pCustomerNumbery pCustomerLevel.

  • Primero, seleccione creditLimitdel cliente especificado por el pCustomerNumberde la customerstabla y guárdelo en la variable local credit.
  • Luego, establezca el valor para el parámetro OUTsi el límite de crédito del cliente es mayor que .pCustomerLevelPLATINUM50,000

Esta declaración encuentra todos los clientes que tienen un límite de crédito mayor que 50,000:

SELECT 
    customerNumber, 
    creditLimit
FROM 
    customers
WHERE 
    creditLimit > 50000
ORDER BY 
    creditLimit DESC;

Aquí está la salida parcial:

Estas declaraciones llaman al GetCustomerLevel()procedimiento almacenado para el cliente 141 y muestran el valor del OUTparámetro pCustomerLevel:

CALL GetCustomerLevel(141, @level);
SELECT @level;

Debido a que el cliente 141 tiene un límite de crédito mayor que 50,000, su nivel se establece PLATINUMcomo se esperaba.

IF-THEN-ELSEdeclaración MySQL

En caso de que desee ejecutar otras declaraciones cuando conditionen la IFrama no se evalúe como TRUE, puede usar la IF-THEN-ELSEdeclaración de la siguiente manera:

IF condition THEN
   statements;
ELSE
   else-statements;
END IF;

En esta sintaxis, si conditionse evalúa como TRUE, se ejecuta statementsentre IF-THENy . ELSEDe lo contrario, el else-statementsentre el ELSEy END IFejecutar.

Modifiquemos el GetCustomerLevel()procedimiento almacenado.

Primero, suelte el GetCustomerLevel()procedimiento almacenado:

DROP PROCEDURE GetCustomerLevel;

Luego, crea el GetCustomerLevel()procedimiento almacenado con el nuevo código:

DELIMITER $$

CREATE PROCEDURE GetCustomerLevel(
    IN  pCustomerNumber INT, 
    OUT pCustomerLevel  VARCHAR(20))
BEGIN
    DECLARE credit DECIMAL DEFAULT 0;

    SELECT creditLimit 
    INTO credit
    FROM customers
    WHERE customerNumber = pCustomerNumber;

    IF credit > 50000 THEN
        SET pCustomerLevel = 'PLATINUM';
    ELSE
        SET pCustomerLevel = 'NOT PLATINUM';
    END IF;
END$$

DELIMITER ;

En este nuevo procedimiento almacenado, incluimos la ELSErama. Si creditno es mayor que 50,000, establecemos el nivel de cliente NOT PLATINUMen el bloque entre ELSEy END IF.

Esta consulta encuentra clientes que tienen un límite de crédito menor o igual 50,000:

SELECT 
    customerNumber, 
    creditLimit
FROM 
    customers
WHERE 
    creditLimit <= 50000
ORDER BY 
    creditLimit DESC;

Esta imagen muestra la salida parcial:

Las siguientes declaraciones llaman al procedimiento almacenado para el número de cliente 447  y muestran el valor del OUTparámetro pCustomerLevel:

CALL GetCustomerLevel(447, @level);
SELECT @level;
declaración mysql if else - salida

El límite de crédito del cliente 447es menor que 50,000, por lo tanto, se ejecuta el extracto en la ELSEsucursal y se establece el valor del OUTparámetro pCustomerLevelen NOT PLATINUM.

IF-THEN-ELSEIF-ELSEdeclaración MySQL

Si desea ejecutar declaraciones condicionalmente basadas en múltiples condiciones, use la siguiente IF-THEN-ELSEIF-ELSEdeclaración:

IF condition THEN
   statements;
ELSEIF elseif-condition THEN
   elseif-statements;
...
ELSE
   else-statements;
END IF;

En esta sintaxis, si conditionse evalúa como TRUE, se ejecuta statementsen la IF-THENrama; de lo contrario, elseif-conditionse evalúa el siguiente.

Si elseif-conditionse evalúa como TRUE, se elseif-statementejecuta; de lo contrario, elseif-conditionse evalúa el siguiente.

La IF-THEN-ELSEIF-ELSEinstrucción puede tener varias ELSEIFramas.

Si ninguna condición en IFy ELSE IFse evalúa como TRUE, se ejecutará else-statementsen la rama.ELSE

Modificaremos el GetCustomerLevel() procedimiento almacenado para usar la IF-THEN-ELSEIF-ELSEdeclaración.

Primero, suelte el GetCustomerLevel()procedimiento almacenado:

DROP PROCEDURE GetCustomerLevel;

Luego, cree el nuevo GetCustomerLevel() procedimiento almacenado que usa la IF-THEN-ELSEIF-ELSEdeclaración.

DELIMITER $$

CREATE PROCEDURE GetCustomerLevel(
    IN  pCustomerNumber INT, 
    OUT pCustomerLevel  VARCHAR(20))
BEGIN
    DECLARE credit DECIMAL DEFAULT 0;

    SELECT creditLimit 
    INTO credit
    FROM customers
    WHERE customerNumber = pCustomerNumber;

    IF credit > 50000 THEN
        SET pCustomerLevel = 'PLATINUM';
    ELSEIF credit <= 50000 AND credit > 10000 THEN
        SET pCustomerLevel = 'GOLD';
    ELSE
        SET pCustomerLevel = 'SILVER';
    END IF;
END $$

DELIMITER ;

En este procedimiento almacenado:

  • Si el crédito es mayor que 50,000, el nivel del cliente es PLATINUM.
  • Si el crédito es menor o igual 50,000y mayor que 10,000, entonces el nivel de cliente es GOLD.
  • De lo contrario, el nivel del cliente es SILVER.

Estas declaraciones llaman al procedimiento almacenado GetCustomerLevel()y muestran el nivel del cliente 447:

CALL GetCustomerLevel(447, @level); 
SELECT @level;

Si prueba el procedimiento almacenado con el cliente que tiene un límite de crédito de 10000 o menos, obtendrá el resultado como SILVER.

En este tutorial, aprendió a usar la IFinstrucción MySQL para ejecutar condicionalmente un bloque de código basado en condiciones específicas.

What is GEEK

Buddha Community

Joe  Hoppe

Joe Hoppe

1595905879

Best MySQL DigitalOcean Performance – ScaleGrid vs. DigitalOcean Managed Databases

HTML to Markdown

MySQL is the all-time number one open source database in the world, and a staple in RDBMS space. DigitalOcean is quickly building its reputation as the developers cloud by providing an affordable, flexible and easy to use cloud platform for developers to work with. MySQL on DigitalOcean is a natural fit, but what’s the best way to deploy your cloud database? In this post, we are going to compare the top two providers, DigitalOcean Managed Databases for MySQL vs. ScaleGrid MySQL hosting on DigitalOcean.

At a glance – TLDR
ScaleGrid Blog - At a glance overview - 1st pointCompare Throughput
ScaleGrid averages almost 40% higher throughput over DigitalOcean for MySQL, with up to 46% higher throughput in write-intensive workloads. Read now

ScaleGrid Blog - At a glance overview - 2nd pointCompare Latency
On average, ScaleGrid achieves almost 30% lower latency over DigitalOcean for the same deployment configurations. Read now

ScaleGrid Blog - At a glance overview - 3rd pointCompare Pricing
ScaleGrid provides 30% more storage on average vs. DigitalOcean for MySQL at the same affordable price. Read now

MySQL DigitalOcean Performance Benchmark
In this benchmark, we compare equivalent plan sizes between ScaleGrid MySQL on DigitalOcean and DigitalOcean Managed Databases for MySQL. We are going to use a common, popular plan size using the below configurations for this performance benchmark:

Comparison Overview
ScaleGridDigitalOceanInstance TypeMedium: 4 vCPUsMedium: 4 vCPUsMySQL Version8.0.208.0.20RAM8GB8GBSSD140GB115GBDeployment TypeStandaloneStandaloneRegionSF03SF03SupportIncludedBusiness-level support included with account sizes over $500/monthMonthly Price$120$120

As you can see above, ScaleGrid and DigitalOcean offer the same plan configurations across this plan size, apart from SSD where ScaleGrid provides over 20% more storage for the same price.

To ensure the most accurate results in our performance tests, we run the benchmark four times for each comparison to find the average performance across throughput and latency over read-intensive workloads, balanced workloads, and write-intensive workloads.

Throughput
In this benchmark, we measure MySQL throughput in terms of queries per second (QPS) to measure our query efficiency. To quickly summarize the results, we display read-intensive, write-intensive and balanced workload averages below for 150 threads for ScaleGrid vs. DigitalOcean MySQL:

ScaleGrid MySQL vs DigitalOcean Managed Databases - Throughput Performance Graph

For the common 150 thread comparison, ScaleGrid averages almost 40% higher throughput over DigitalOcean for MySQL, with up to 46% higher throughput in write-intensive workloads.

#cloud #database #developer #digital ocean #mysql #performance #scalegrid #95th percentile latency #balanced workloads #developers cloud #digitalocean droplet #digitalocean managed databases #digitalocean performance #digitalocean pricing #higher throughput #latency benchmark #lower latency #mysql benchmark setup #mysql client threads #mysql configuration #mysql digitalocean #mysql latency #mysql on digitalocean #mysql throughput #performance benchmark #queries per second #read-intensive #scalegrid mysql #scalegrid vs. digitalocean #throughput benchmark #write-intensive

joe biden

1617255938

¿Cómo migrar los buzones de correo de Exchange a la nube de Office 365?

Si tiene problemas para migrar los buzones de correo de Exchange a Office 365, debe leer este artículo para saber cómo migrar los buzones de correo de Exchange EDB a Office 365. Al migrar a Office 365, los usuarios pueden acceder a sus buzones de correo desde cualquier lugar y desde cualquier dispositivo.

En esta publicación, explicaremos las razones detrás de esta migración y una solución profesional para migrar de Exchange a Office 365.

Razones para migrar Exchange Server a la nube de Office 365

Office 365 apareció por primera vez en 2011 y, dado que se considera la mejor plataforma para aquellas organizaciones que desean administrar todo su sistema de correo electrónico en la nube. Estas son las características clave de Office 365:

  1. Permite trabajar desde cualquier lugar y desde cualquier lugar.
  2. No se preocupe por el spam y el malware.
  3. La seguridad proporcionada por Office 365 es altamente confiable.
  4. Controla el costo total y brinda flexibilidad financiera.
  5. Todas las actualizaciones y mejoras son administradas por Microsoft.

¿Cómo migrar los buzones de correo de Exchange a Office 365?

Hay varias formas manuales de migrar los buzones de correo de Exchange EDB a Office 365, pero para evitar estos complicados y prolongados procedimientos, presentamos una solución de terceros, es decir, la herramienta de migración de Exchange, que es automatizada y directa para la migración de Exchange a Office 365. La herramienta funciona rápidamente y migra todos los elementos del buzón de Exchange Server a Office 365.

La herramienta de migración de Datavare Exchange es demasiado fácil de usar y ofrece pasos sencillos para migrar EDB a Office 365:

  1. Descargue e instale el software en su sistema.
  2. Agregue el archivo EDB de Exchange con el botón Examinar.
  3. Seleccione exportar a buzones de correo de Office 365.
  4. Proporcione los detalles de inicio de sesión de la cuenta de Office 365.
  5. Seleccione la carpeta y presione el botón Finalizar.

Por lo tanto, todos sus buzones de correo de Exchange EDB ahora se migran a Office 365.
Nota: puede usar filtros para migrar los elementos de datos deseados de la cuenta de Exchange a la de Office 365

Líneas finales

Este blog le indica una solución profesional para la migración de buzones de correo de Exchange a la cuenta de Office 365. Dado que las soluciones manuales son complicadas, sugerimos la herramienta de migración de Exchange, que es demasiado simple de usar. Los usuarios no se enfrentan a problemas al operar el programa. La mejor parte de este software es que no necesita habilidades técnicas para realizar la migración. Se puede comprender el funcionamiento del software descargando la versión de demostración que permite la migración de los primeros 50 elementos por carpeta.

Más información:- https://www.datavare.com/software/edb-migration.html

#herramienta de migración de intercambio #migración de intercambio #migrar buzones de correo de exchange

Loma  Baumbach

Loma Baumbach

1595781840

Exploring MySQL Binlog Server - Ripple

MySQL does not limit the number of slaves that you can connect to the master server in a replication topology. However, as the number of slaves increases, they will have a toll on the master resources because the binary logs will need to be served to different slaves working at different speeds. If the data churn on the master is high, the serving of binary logs alone could saturate the network interface of the master.

A classic solution for this problem is to deploy a binlog server – an intermediate proxy server that sits between the master and its slaves. The binlog server is set up as a slave to the master, and in turn, acts as a master to the original set of slaves. It receives binary log events from the master, does not apply these events, but serves them to all the other slaves. This way, the load on the master is tremendously reduced, and at the same time, the binlog server serves the binlogs more efficiently to slaves since it does not have to do any other database server processing.

MySQL Binlog Server Deployment Diagram - ScaleGrid Blog

Ripple is an open source binlog server developed by Pavel Ivanov. A blog post from Percona, titled MySQL Ripple: The First Impression of a MySQL Binlog Server, gives a very good introduction to deploying and using Ripple. I had an opportunity to explore Ripple in some more detail and wanted to share my observations through this post.

1. Support for GTID based replication

Ripple supports only GTID mode, and not file and position-based replication. If your master is running in non-GTID mode, you will get this error from Ripple:

Failed to read packet: Got error reading packet from server: The replication sender thread cannot start in AUTO_POSITION mode: this server has GTID_MODE = OFF instead of ON.

You can specify Server_id and UUID for the ripple server using the cmd line options: -ripple_server_id and -ripple_server_uuid

Both are optional parameters, and if not specified, Ripple will use the default server_id=112211 and uuid will be auto generated.

2. Connecting to the master using replication user and password

While connecting to the master, you can specify the replication user and password using the command line options:

-ripple_master_user and -ripple_master_password

3. Connection endpoint for the Ripple server

You can use the command line options -ripple_server_ports and -ripple_server_address to specify the connection end points for the Ripple server. Ensure to specify the network accessible hostname or IP address of your Ripple server as the -rippple_server_address. Otherwise, by default, Ripple will bind to localhost and hence you will not be able to connect to it remotely.

4. Setting up slaves to the Ripple server

You can use the CHANGE MASTER TO command to connect your slaves to replicate from the Ripple server.

To ensure that Ripple can authenticate the password that you use to connect to it, you need to start Ripple by specifying the option -ripple_server_password_hash

For example, if you start the ripple server with the command:

rippled -ripple_datadir=./binlog_server -ripple_master_address= <master ip> -ripple_master_port=3306 -ripple_master_user=repl -ripple_master_password='password' -ripple_server_ports=15000 -ripple_server_address='172.31.23.201' -ripple_server_password_hash='EF8C75CB6E99A0732D2DE207DAEF65D555BDFB8E'

you can use the following CHANGE MASTER TO command to connect from the slave:

CHANGE MASTER TO master_host='172.31.23.201', master_port=15000, master_password=’XpKWeZRNH5#satCI’, master_user=’rep’

Note that the password hash specified for the Ripple server corresponds to the text password used in the CHANGE MASTER TO command. Currently, Ripple does not authenticate based on the usernames and accepts any non-empty username as long as the password matches.

Exploring MySQL Binlog Server - Ripple

CLICK TO TWEET

5. Ripple server management

It’s possible to monitor and manage the Ripple server using the MySQL protocol from any standard MySQL client. There are a limited set of commands that are supported which you can see directly in the source code on the mysql-ripple GitHub page.

Some of the useful commands are:

  • SELECT @@global.gtid_executed; – To see the GTID SET of the Ripple server based on its downloaded binary logs.
  • STOP SLAVE; – To disconnect the Ripple server from the master.
  • START SLAVE; – To connect the Ripple server to the master.

#cloud #database #developer #high availability #mysql #performance #binary logs #gtid replication #mysql binlog #mysql protocol #mysql ripple #mysql server #parallel threads #proxy server #replication topology #ripple server

Whitney  Durgan

Whitney Durgan

1618911221

Setting MySQL Configuration Variables - MySQL 5.7 vs MySQL 8.0

In this article, we will explain the differences in managing the configuration variables between MySQL 5.7 and MySQL 8.0.

MySQL configuration variables are a set of server system variables used to configure the operation and behavior of the server. In this blog post, we will explain the differences in managing the configuration variables between MySQL 5.7 and MySQL 8.0.

We will explain three different ways for setting the configuration variables based on your use-case. Configuration variables that can be set at run-time are called Dynamic variables and those that need a MySQL server restart to take effect are called Non-Dynamic variables.

#mysql #mysql 5.7 #mysql server #mysql 8.0

Devyn  Reilly

Devyn Reilly

1618900707

Setting MySQL Configuration Variables – MySQL 5.7 vs MySQL 8.0

MySQL configuration variables are a set of server system variables used to configure the operation and behavior of the server. In this blog post, we will explain the differences in managing the configuration variables between MySQL 5.7 and MySQL 8.0.

We will explain three different ways for setting the configuration variables based on your use-case. Configuration variables that can be set at run time are called Dynamic variables and those that need a MySQL server restart to take effect are called Non-Dynamic variables.

Setting MySQL Configuration Variables

#mysql #mysql 5.7 #mysql 8.0 #mysql server