Ed *_*eal 6 mysql sql scripting
我有一个脚本,我用它来构建表和存储过程.例如,我有一个类型的列varchar
.varchar
需要一个大小参数,该大小我也用作存储过程和这些过程中的参数.
是否可以#define
为其大小提供a的等价物,因此我可以轻松调整大小而无需通过整个脚本进行更改?
我正在使用MySql工作台.
编辑
我曾尝试SET
和DECLARE
我有一个脚本 - 这是(删节)
CREATE TABLE `locations`
(
`location` VARCHAR(25) NOT NULL
);
...
CREATE PROCEDURE AddLocation (IN location VARCHAR(25)
BEGIN
...
END$$
Run Code Online (Sandbox Code Playgroud)
我想要实现的是用一个常量替换脚本中的值25 - 类似于#define
创建表和存储过程的脚本顶部的一个,所以我能够轻松地将25更改为另一个数字.
有人找到了解决这个问题的方法吗?
Mar*_*lff 20
C预处理器(cpp)在历史上与C(因此名称)相关联,但它实际上是可以用于(或滥用)其他内容的通用文本处理器.
考虑这个名为location.src的文件(稍后会详细介绍).
// C++ style comments works here
/* C style works also */
-- plain old SQL comments also work,
-- but you should avoid using '#' style of comments,
-- this will confuse the C pre-processor ...
#define LOCATION_LEN 25
/* Debug helper macro */
#include "debug.src"
DROP TABLE IF EXISTS test.locations;
CREATE TABLE test.locations
(
`location` VARCHAR(LOCATION_LEN) NOT NULL
);
DROP PROCEDURE IF EXISTS test.AddLocation;
delimiter $$
CREATE PROCEDURE test.AddLocation (IN location VARCHAR(LOCATION_LEN))
BEGIN
-- example of macro
ASSERT(length(location) > 0, "lost or something ?");
-- do something
select "Hi there.";
END
$$
delimiter ;
Run Code Online (Sandbox Code Playgroud)
和文件debug.src,包括:
#ifdef HAVE_DEBUG
#define ASSERT(C, T) \
begin \
if (not (C)) then \
begin \
declare my_msg varchar(1000); \
set my_msg = concat("Assert failed, file:", __FILE__, \
", line: ", __LINE__, \
", condition ", #C, \
", text: ", T); \
signal sqlstate "HY000" set message_text = my_msg; \
end; \
end if; \
end
#else
#define ASSERT(C, T) begin end
#endif
Run Code Online (Sandbox Code Playgroud)
编译时:
cpp -E location.src -o location.sql
Run Code Online (Sandbox Code Playgroud)
你得到了你正在寻找的代码,cpp扩展了#define值.
编译时:
cpp -E -DHAVE_DEBUG location.src -o location.sql
Run Code Online (Sandbox Code Playgroud)
你得到相同的,加上ASSERT宏(作为奖金发布,以显示可以做什么).
假设在测试环境中部署了HAVE_DEBUG(在使用SIGNAL后为5.5或更高版本),结果如下所示:
mysql> call AddLocation("Here");
+-----------+
| Hi there. |
+-----------+
| Hi there. |
+-----------+
1 row in set (0.00 sec)
Query OK, 0 rows affected (0.00 sec)
mysql> call AddLocation("");
ERROR 1644 (HY000): Assert failed, file:location.src, line: 24, condition length(location) > 0, text: lost or something ?
Run Code Online (Sandbox Code Playgroud)
请注意文件名,行号和条件如何指向location.src中引发断言的源代码中的位置,再次感谢C预处理器.
现在,关于".src"文件扩展名:
编辑:最初发布为.xql,为了清楚起见重命名为.src.这里没有与xml查询相关的任何内容.
与任何工具一样,使用cpp可以带来好处,而以便携方式维护LOCATION_LEN的用例看起来非常合理.它也可能导致坏事,有太多#include,嵌套#ifdef地狱,宏等等,最后会混淆代码,所以你的里程可能会有所不同.
有了这个答案,你会得到整个事情(#define
,#include
,#ifdef
,__FILE__
,__LINE__
,#C
,命令行选项来建立),所以我希望它应该涵盖一切.