I need to pass column names using variable in select statement in Store Procedure but i cannot use dynamic query
One way to do this without using dynamic sql is using CASE statement
But this is ugly
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
You have to check all the column's in CASE
statement.
You can't parameterize identifiers in Sql server, and I doubt it's possible in any other relational database.
Your best choice is to use dynamic Sql.
Note that dynamic sql is very often a security hazard and you must defend your code from sql injection attacks.
I would probably do something like this:
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
This way you make sure that the column names actually exists in the table, as well as using QUOTENAME
as another layer of safety.
Note: in your presentation layer you should handle the option that the select will not be performed since the column names are invalid.