Background: There\'s a stored procedure which does \"stuff\" with a temp table of a given name. The procedure is generic in that it inspects the schema of the temp table and
Instead of #test, use a fully qualified name. For example,
[tempdb].[dbo].[temptable]
I learned this little trick here Insert result of executing dynamic query into a table .
Intellisense will complain but you will still be able to create or alter the stored procedure.
When done with it, be sure to drop it:
DROP TABLE [tempdb].[dbo].[temptable]
It's a limitation. Dynamic SQL won't work either since #tmp will be created in a new session and immediately lost. For the EXACT snippet as shown, this does the same
CREATE TABLE #test
(
a BIGINT NOT NULL,
b BIGINT NOT NULL
)
IF not (1=1)
ALTER TABLE #test ADD c BIGINT NOT NULL
There cannot be two CREATE .. #name within the same batch, but this will also work in general form
IF (1=1)
BEGIN
CREATE TABLE #test
(
a BIGINT NOT NULL,
b BIGINT NOT NULL
);
END
GO
IF NOT (1=1)
BEGIN
CREATE TABLE #test
(
a BIGINT NOT NULL,
b BIGINT NOT NULL,
c BIGINT NOT NULL
)
END
since i dont have sql 2008, i cannot test it. however as far as i know, this is a parser issue explicitly with temp tables. the same would work fine with normal tables
to sort this out, just split your code with logical GO statements
ideally: check for existence of temp tables before you create your temp tables, drop them if they exist, fire a go, do the creation of temp tables again, fire a go, then any post processing, fire a go, finally drop them again and fire the last go
you might also want to try and use the table variable instead of temp tables if above does not solve it for you
You could always "cheat":
DECLARE @SQL VARCHAR(200)
IF (1=1)
BEGIN
SET @SQL = 'CREATE TABLE #Temp ' +
'( ' +
' a BIGINT NOT NULL, ' +
' b BIGINT NOT NULL ' +
') '
END
ELSE
BEGIN
SET @SQL = 'CREATE TABLE #Temp ' +
'( ' +
' a BIGINT NOT NULL, ' +
' b BIGINT NOT NULL, ' +
' c BIGINT NOT NULL ' +
') '
END
EXEC SP_EXECUTESQL @SQL