Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assertion in MySQL

Tags:

sql

mysql

assert

I have a SQL script to run against a large database. I'd like to put a couple of simple queries at the start, just as a sanity check.

Is there any way to write an assertion in MySQL? Or any kind of "select ..., and if it doesn't match this value, then abort the entire script"?

like image 361
Ken Avatar asked Aug 24 '10 19:08

Ken


People also ask

What is database assertion?

An assertion is a statement in SQL that ensures a certain condition will always exist in the database. Assertions are like column and table constraints, except that they are specified separately from table definitions.

What is assertion and trigger?

Triggers are very well used in modern databases. Assertions can't modify the data and they are not linked to any specific tables or events in the database but Triggers are more powerful because they can check conditions and also modify the data within the tables inside a database, unlike assertions.

What is SQL Server assertion?

Assertions are checked conditions in the SQL Anywhere server that prevent data corruptions during operation.


3 Answers

Some crazy code. Main point is: SET could raise error for mysql variables.

For example.

 SET @value = 0;
 SET SESSION sql_mode = if(@value, @@SESSION.sql_mode, 'something wrong uphere'); 

Would output ERROR 1231 (42000): Variable 'sql_mode' can't be set to the value of 'something wrong uphere' and execution would be stopped.

This approach is not semantic but it works.

like image 190
sectus Avatar answered Sep 19 '22 17:09

sectus


You could put the entire script in an if statement, depending on what kind of value you need to check, here's an example:

DECLARE @value int
SET @value = (SELECT COUNT(*) FROM dbo)

IF @value >0
BEGIN
 --Do Stuff Here
END
like image 33
Brett Avatar answered Sep 18 '22 17:09

Brett


You can also do this via a stored procedure / function, as in the example below:

CREATE FUNCTION `RunProcess`() RETURNS INT(11)
runProcess:BEGIN

DECLARE check_value INT;
DECLARE error_code INT;

SELECT COUNT(*) FROM dbo INTO check_value;

IF check_value = 0 THEN set error_code = 666;
    LEAVE runProcess;
    RETURN error_code;
END IF;

...
...
END;
like image 30
schizix Avatar answered Sep 18 '22 17:09

schizix