实现思路:mysql创建view时不允许绑定用户变量,我们可以通过一个函数来返回用户变量,达到我们想要效果(通过用户变量创建动态view) 1、创建test_sp,在sp中给@company用户变量赋值 2、创建函数test_f,函数定义返回值为varchar,函数直接返回用户变量@company 3、创建视图,test_v,将函数test_f绑定到视图创建视图语句上,例如: create view test_view AS select company_code,value from test where company_code = test_f(); 4、返回test_sp中调用test_v。
详细代码如下:大家可以测试玩玩 创建test表
创建test_f函数,返回@company create FUNCTION test_f() returns varchar(20) BEGIN return @company; END; 创建视图test_view,将条件company_code绑定函数test_f create view test_view AS select company_code,value from test where company_code = test_f(); 创建存储过程 drop procedure if exists test_sp; create procedure test_sp( in company_code varchar(20) ) BEGIN set @company = company_code; select * from test_view; END; 验证结果