我有一個存盤程序,其中列名作為字串出現在引數中 - varchar
如何將其轉換為列名以在 select/insert/update 中查詢,因為列名應該是
colnName
謝謝
如何將傳入的字串轉換為存盤程序中的列名
uj5u.com熱心網友回復:
據我所知,在執行查詢時不能使用變數定義列名。它們必須是硬編碼的。因此,我們應該在撰寫陳述句時專注于對列名進行硬編碼,而不是在執行查詢時動態確定列名。MySQLPREPARE陳述句是一個可行的選擇。如果您感興趣,這里是測驗樣本。
drop table if exists test;
create table test (id int);
delimiter //
drop procedure if exists str_to_colname //
create procedure str_to_colname(colnName varchar(15))
begin
set @insert_stmt=concat('insert test (',colnName,') values(1),(2),(3);'); -- we make our first statement into a user variable, which will be used as a source for PREPARE
prepare inst from @insert_stmt; -- define the prepared statement using our user variable
execute inst; -- this is like executing a query using the literal values of the user variable
deallocate prepare inst; -- remove the prepare after its execution
set @select_stmt=concat('select ',colnName,' from test;'); -- here is the user variable which stores our second statement
prepare sel from @select_stmt;
execute sel;
deallocate prepare sel;
end//
delimiter ;
call str_to_colname('id'); -- here we use the column name `id` as the parameter
--result set:
# id
1
2
3
uj5u.com熱心網友回復:
但是你可以有多個 if 條件來解決問題。
也是可以的
解決方案 1 - FLY 上的 SQL 查詢 - 但它只能執行 解決方案 2 - 動態 SQL - 我們不能添加列名,因為它是一個字串。
我們需要使用 CASE 和 WHEN 和 THEN 并創建查詢 (OR) IF THEN
IF(columnName='product') THEN select productfrom purchase IF(columnName='test') THEN selecttest from purchase
這樣我們就可以解決了。所以這兩種選擇都是可能的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/521043.html
標籤:mysql存储过程
