Muh*_*lal 0 sql database sql-server sql-server-2008
这是我下面的SQL查询.我想从作为变量给出的列名中选择值.除了使用动态查询之外,有没有合适的方法?
SELECT EPV.EmployeeCode, @RateOfEmployee, @RateOfEmployer
FROM [HR_EmployeeProvisions] EPV
Run Code Online (Sandbox Code Playgroud)
不使用动态sql的一种方法是使用CASE语句
但这很难看
SELECT EPV.EmployeeCode, case @RateOfEmployee when 'RateOfEmployee' then RateOfEmployee
when 'X' then X
..
end , case @RateOfEmployer when 'RateOfEmployer' then RateOfEmployer
when 'Y' then Y
..
end
FROM [HR_EmployeeProvisions] EPV
Run Code Online (Sandbox Code Playgroud)
您必须检查CASE语句中的所有列.
您无法在Sql server中参数化标识符,我怀疑它是否可以在任何其他关系数据库中使用.
您最好的选择是使用动态Sql.
请注意,动态sql通常是一个安全隐患,您必须保护您的代码免受SQL注入攻击.
我可能会这样做:
Declare @Sql nvarchar(500)
Declare numberOfColumns int;
select @numberOfColumns = count(1)
from information_schema.columns
where table_name = 'HR_EmployeeProvisions'
and column_name IN(@RateOfEmployee, @RateOfEmployer)
if @numberOfColumns = 2 begin
Select @Sql = 'SELECT EmployeeCode, '+ QUOTENAME(@RateOfEmployee) +' ,'+ QUOTENAME(@RateOfEmployer) +
'FROM HR_EmployeeProvisions'
exec(@Sql)
end
Run Code Online (Sandbox Code Playgroud)
这样,您可以确保列名实际存在于表中,以及使用QUOTENAME另一层安全性.
注意:在表示层中,您应该处理由于列名无效而不会执行选择的选项.