下面的SQL代码返回值4.68
select Top 1 [Price_per_KG_AES001] as [(316) 401 - 600] From [dbo].[tbl_stock_list] where [GRADE] = '316'
当我将Customer作为参数变量时,下面的SQL返回Price_per_KG_AES001
Declare @TheCustomer varchar(50) = 'Price_per_KG_AES001'
select Top 1 @TheCustomer as [(316) 401 - 600] From [dbo].[tbl_stock_list] where [GRADE] = '316'
如何修改代码以使用变量返回4.68?
答案 0 :(得分:2)
您需要动态SQL,当前语法似乎不起作用。
因此,您需要:
Declare @TheCustomer varchar(50) = 'Price_per_KG_AES001'
declare @sql varchar(500)
set @sql = 'select Top 1 '+ @TheCustomer +' as [(316) 401 - 600]
from [dbo].[tbl_stock_list]
where [GRADE] = ''316'' '
print @sql -- to see how your query looks before execution
exec (@sql);
答案 1 :(得分:1)
您需要做的是将变量的内容替换为查询,然后执行它。
像这样...
DECLARE
@TheCustomer VARCHAR(50) = 'Price_per_KG_AES001',
@sql_statement VARCHAR(MAX)
SET @sql_statement = 'select Top 1 ' + @TheCustomer + ' as [(316) 401 - 600] From [dbo].[tbl_stock_list] where [GRADE] = ''316'''
EXEC @sql_statement
(另外,请使用sp_executesql
:https://docs.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sp-executesql-transact-sql?view=sql-server-2017来查看参数化查询)
但是,如果有人设法“破解”该变量的内容,并在其中放入一些SQL,则将执行其SQL。请参阅SQL注入攻击。
保护自己的安全方法是创建允许值的白名单。只有变量内容在列表中,您才可以继续。
或者,只需使用CASE
语句。
SELECT
TOP(1)
CASE WHEN @var = 'x' THEN table.x
WHEN @var = 'y' THEN table.y
WHEN @var = 'z' THEN table.z END AS column_alias
FROM
table