0

In a select statement, in from clause, table name changes depending on a parameter. I tried:

from
IIf(@prmdataVal ='Dummy', tbl1, tbl2) T1

It's showing an error. How to do this?

Tavish Aggarwal
  • 1,020
  • 3
  • 22
  • 51
Mish
  • 35
  • 6
  • Did you already try to use dynamic SQL? You can't change the from part of a query except in dynamic SQL... – Tyron78 Oct 04 '17 at 10:38
  • Possible duplicate of [Table name as variable](https://stackoverflow.com/questions/2838490/table-name-as-variable). Or (if it's always exactly those two tables) [this one](https://stackoverflow.com/q/7533539/4137916). – Jeroen Mostert Oct 04 '17 at 10:39
  • This kind of pattern generally indicates a database modelling issue – Nick.Mc Oct 04 '17 at 10:43

2 Answers2

2

Try something like the following:

DECLARE @stmt nvarchar(max);
SELECT @stmt = 'SELECT * FROM ' + CASE WHEN @prmdataVal = 'Dummy' THEN 'tbl1' ELSE 'tbl2' END
EXEC @stmt
Tyron78
  • 4,117
  • 2
  • 17
  • 32
0

Declaring a variable for table name and then calling it in the from clause of dynamic SQL, worked.

Declare @TblName AS SYSNAME = CASE WHEN @prmdataVal='Dummy' THEN 'tbl1'
ELSE 'tbl2' end

and then calling it in the dynamic sql:

from '+@TblName +' as T1...
Mish
  • 35
  • 6