|
|
Question : Problems with stored procedure and SELECT INTO
|
|
In a stored procedure I try to use two conditional SELECT INTO statements which select into the same temporary table, but they create an error.
. . . if @inst_type_id = '1' begin select d.ORG_ID, d.REPORTING_TYPE_ID, d.REPORTING_PERIOD, d.FINANCIAL_PERIOD, #incremental.CREATION_ID, #incremental.CREATION_DATE, EXTRACT = 0 into #dvc from MAIN..DVC d, MAIN..INSTALL_ID_ORG io, MAIN..INSTALLATION_ID i, #auth, #incremental where i.ME_IND = 'Y' and i.INSTALLATION_ID = io.INSTALLATION_ID and io.ORG_ID = d.ORG_ID and io.ORG_ID = #auth.ORG_ID and d.ORG_ID = #incremental.ORG_ID and d.REPORTING_PERIOD = #incremental.REPORTING_PERIOD and d.FINANCIAL_PERIOD = #incremental.FINANCIAL_PERIOD end
if @inst_type_id = '2' begin select ORG_ID, REPORTING_TYPE_ID, REPORTING_PERIOD, FINANCIAL_PERIOD, CREATION_ID = null, CREATION_DATE = null, EXTRACT = 1 into #dvc from MAIN..ORDER_ITEM_DVC where ORACLE_STATUS = -1 end .. .
When I create the procedure I get the error message: There is already an object named '#dvc' in the database.
I know I can use a create table #dvc ... first and then insert the records, but I understand from a performance point of view, it is better to use SELECT .. INTO
Can this be achieved in a stored procedure?
We use Sybase ASE 12.5
|
Answer : Problems with stored procedure and SELECT INTO
|
|
The problem is that a "select into" is an implicit CREATE TABLE command. The compiler sees that there are two commands to create the same table and unfortunately doesn't recognize that only one of those statements will actually be executed. This is actually intentional I believe, and I wouldn't expect it to change.
A possible way around this might be to select all this with a null set, which should create the table. Sort of like Select a, b, c from TableX where 1-2. I believe this will create the table for you and set up all your columns. Then you can do a simple insert, and you should be fine.
If not, you'll have to create the table upfront and specify all the columns and have standard insert statements within the if-end sections.
I know this seems like extra BS to go through, but this does actually help the code be more maintanable. Having two possible "select into" branches raises the possibility that the tables won't be identical, and it's a pain tracking down a bug like that when it shows up.
Greg
|
|
|
|
|