Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
Syntax checker
Message
From
29/01/2004 16:01:47
 
 
To
29/01/2004 15:31:40
General information
Forum:
Microsoft SQL Server
Category:
Stored procedures, Triggers, UDFs
Title:
Miscellaneous
Thread ID:
00872021
Message ID:
00872045
Views:
19
>Hi everyone,
>I am writing SP and getting a error message for logic like this:
>
>IF EXISTS (SELECT *FROM [tempdb].INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME LIKE '#MainView___%') DROP TABLE #MainView
>
>IF @State = ''
> SELECT * INTO #MainView FROM main WHERE CONVERT(varchar, date, 101)=@Date
>ELSE
> SELECT * INTO #MainView FROM main WHERE CONVERT(varchar, date, 101)=@Date AND State=@State
>
>It says that object #MainView already exists in database
>What do I do wrong?
>Thanks in advance

The compiler doesn't differentiate between the two parts of the IF..ELSE, so it has presumed the creation of the temp table in the IF before trying to compile the ELSE where it assumes another table creation, hence the error.

Prior to the IF..ELSE, you can either:
- Create the temp table using CREATE TABLE... (since you probably already know the structure)
- If you don't necessarily know (or need to know) the structure, you can SELECT TOP 0 * INTO... the temp table.

and then in the IF, do an INSERT INTO the temp table

FWIW: You'll typically get better performance with a CREATE TABLE, because some sys tables get locked with SELECT INTO.
Insanity: Doing the same thing over and over and expecting different results.
Previous
Next
Reply
Map
View

Click here to load this message in the networking platform