Assertion in MySQL

半城伤御伤魂 提交于 2019-12-23 08:50:27

问题


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"?


回答1:


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.




回答2:


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



回答3:


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;


来源:https://stackoverflow.com/questions/3560149/assertion-in-mysql

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!