Reputation: 324
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"?
Upvotes: 10
Views: 6942
Reputation: 1893
One way to go about this could be to make an insert fail on purpose if you assertion fails. This is not pretty, but it is simple and it works.
Let's say Table1 contains columnA and columnB. You want to insert into this table the values ('any', 'thing')
, but ONLY if these values fulfil some conditions.
Then do something like this:
SELECT 'any', 'thing' INTO @setA, @setB FROM DUAL WHERE ( your conditions...);
INSERT INTO Table1 (columnA, columnB) VALUES (@setA, @setB);
the 'any' and 'thing' values would obviously be inserted at runtime in the query. If you Table1 is set up to accept only non-null values in column A or B, this will fail when your conditions fail.
A very simple nonsensical example (this obviously can be achieved otherwise, this is only an example :-) ), if you want the values to differ:
SELECT 'any', 'thing' INTO @setA, @setB FROM DUAL WHERE ( 'a'!='b');
INSERT INTO Table1 (columnA, columnB) VALUES (@setA, @setB);
The test condition doesn't have to be on the values you are trying to insert:
SELECT 'any', 'thing' INTO @setA, @setB FROM DUAL WHERE ( 'another' IS NOT NULL);
INSERT INTO Table1 (columnA, columnB) VALUES (@setA, @setB);
If your goal is not to do perform an insert, the same logic can be applied on different transaction types, the idea being to alter the variables so they make the query fail.
Or you can create a dummy table just for this purpose, with a non-null column, and always insert your assertion result in the dummy table's first row. Not pretty, but it works :-)
Upvotes: 0
Reputation: 15464
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.
Upvotes: 8
Reputation: 25
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;
Upvotes: 1
Reputation: 4061
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
Upvotes: 3