I am currently trying to DECLARE a variable, @MyTable, as a user defined table type (udtt). However, which udtt it is declared as depends on the value of the variable @Schema. To do this, I have made the following attempts:
Attempt One:
IF (@Schema = 'sch_A') DECLARE @MyTable [sch_A].[udtt_Table]
IF (@Schema = 'sch_B') DECLARE @MyTable [sch_B].[udtt_Table]
IF (@Schema = 'sch_C') DECLARE @MyTable [sch_C].[udtt_Table]
Attempt Two:
DECLARE @sql = 'DECLARE @MyTable [' + @Schema + '].[udtt_Table]'
The problem with my fisrt attempt is that the variable @MyTable is declared by every IF statement, even when evaluated as false. This results in an error, stating that the variable @MyTable has already been declared, being thrown. This issue is discussed here.
The problem with my second is also to do with the scope of the variable @MyTable - although my understanding of why this is the case is more limited.
Can anyone suggest a way in which the desired result may be achieved?