我正在嘗試獲取它,以便我可以在列名中使用一個變數,但它似乎不起作用。
select
v.name as concat(@person,'\'s Vendor')
,sum(t.amount) as 'Total'
from
total t
inner join vendor v
on v.d = t.d
where
t.who = @person
and v.name is not null
and t.sub_cat not like 'Payment'
and year(date) = (year(sysdate())-1)
and amount > 0
group by
v.name
order by
sum(amount)
desc limit 20;
上面會引發錯誤,但下面會起作用。
select
v.name as 'John\'s Vendor'
,sum(t.amount) as 'Total'
from
total t
inner join vendor v
on v.d = t.d
where
t.who = @person
and v.name is not null
and t.sub_cat not like 'Payment'
and year(date) = (year(sysdate())-1)
and amount > 0
group by
v.name
order by
sum(amount)
desc limit 20;
基本上,我希望能夠添加人員變數和更多文本作為列名,以更好地識別資料的用途,在這種情況下,資料是關于誰的。另外,我想將其用作存盤程序:
create procedure GetTotals(IN person varchar(10));
delimiter //
begin
above working code
end //
delimiter ;
uj5u.com熱心網友回復:
為什么不將引數添加為具有固定列名的自己的列。您的退貨流程將負責展示,并且可以使用該額外的列作為“誰”來達到目的。前任:
select
v.name,
sum(t.amount) as 'Total',
concat(@person,'\'s Vendor') as ForWho
from
是的,每一行都會在 ForWho 列中回傳 ex: "John's Vendor" 的結果,但至少你不必在回傳集中格式化它,你有這個列。
uj5u.com熱心網友回復:
識別符號(包括別名)必須在決議查詢時固定。您不能創建依賴于運算式的別名。
您可以通過使用@person變數格式化 SQL 陳述句來進行動態 SQL 查詢:
SET @sql = CONCAT(
'select v.name as `', concat(@person,'\'s Vendor'), '`,',
...
' where t.who = ? ',
...
);
PREPARE stmt FROM @sql;
EXECUTE stmt USING @person;
DEALLOCATE PREPARE stmt;
的值@person可以設定為?占位符出現在準備好的查詢語法中的引數。但是列別名中的用法不能引數化。所以你只需要注意@person在那個位置使用的值是安全的。
您應該像任何其他識別符號一樣使用反引號分隔別名,以防止在@person包含空格或標點字符時出現語法錯誤。
uj5u.com熱心網友回復:
您可以對此類查詢使用動態 sql
SET @sql = CONCAT("select
v.name as '",@person,
"\\'s Vendor'
,sum(t.amount) as 'Total'
from
total t
inner join vendor v
on v.d = t.d
where
t.who = @person
and v.name is not null
and t.sub_cat not like 'Payment'
and year(date) = (year(sysdate())-1)
and amount > 0
group by
v.name
order by
sum(amount)
desc limit 20;");
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
請記住 thsi 可用于 sql 注入,因此名稱的白名單是有序的
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/436650.html
上一篇:從SQL中獲取所有包含特定值的值
