Before you shout at me in CAPS for not searching - I have! Dynamic SQL is good, dynamic SQL is bad. Learning a lot..
I can accomplish what I'm after by using logic in there WHERE clause, but it adds a significant amount of run time. The query takes 8 seconds if I hard code the criteria and 1:20 if I use the WHERE logic.
Here is what I'd like to do:
Declare @EmployeeToggle varchar(30)
Declare @Employee_ID varchar(30)
Declare @EmployeeField varchar(100)
set @EmployeeToggle = '1'
set @Employee_ID = '1166'
set @EmployeeField = case when @EmployeeToggle = '1' then 'Field1' else
'Field2' end;
select * from Table1 where @EmployeeField = @Employee_ID
I don't think it's possible without dynamic sql. I still don't know whether or not I should use it. It's my thought that it would take the query back down to 8 seconds, because it would immediately know which field to use in the where clause.
Alternatively, a few ways to do it in the where only:
where (( not @EmployeeToggle = '1') or Field1 = @Employee_ID) and
(@EmployeeToggle = '1' or Field2 = @Employee_ID)
where (1=(case when @EmployeeToggle = '1' then 1 else 0 end ) or Field1 =
@Employee_ID)
and (1=(case when @EmployeeToggle = '2' then 1 else 0 end) or Field2 =
@Employee_ID)
These work great (admittedly I copied and pasted these examples), but at the expense of run time.
My final thought, and the way others have done it at my org, is to create two scripts that are identical except for the field used in the where clause. So, if @EmployeeToggle = '1' it will run the first script and if it's '2' it will run the second. I haven't tried that yet, but I assume the runtime will be closer to the 8 seconds at the expense of some ugly code.
Thanks for the help.