2

I am creating a stored procedure but it throws an error. Can anybody tell me if there is something i am doing wrong.

CREATE TABLE tbl1 (ID int)
INSERT INTO tbl1 SELECT 1
CREATE TABLE tbl2 (ID int)
INSERT INTO tbl2 SELECT 2

CREATE PROCEDURE QOTD (@source INT)
AS 
BEGIN
 IF @source = 1 
 SELECT ID INTO #tmpID FROM tbl1 
 ELSE
 SELECT ID INTO #tmpID FROM tbl2 

 SELECT ID FROM #tmpID
END

ERROR:There is already an object named '#tmpID' in the database.

1
  • 1
    @Mitch Wheat, how do you explain that error at compile time though? I'm pretty sure it's because it is a syntax error to do SELECT ID INTO #tmpID FROM tbl1 and not because the object already exists. Commented Nov 18, 2010 at 12:11

3 Answers 3

7

Sometimes the T-SQL compiler gets confused, and doesn't realise that only one side of an IF would be followed.

CREATE PROCEDURE QOTD (@source INT)
AS 
BEGIN
 CREATE TABLE #tmpID(ID int)
 IF @source = 1 
 INSERT INTO #tmpID SELECT ID FROM tbl1 
 ELSE
 INSERT INTO #tmpID SELECT ID  FROM tbl2 

 SELECT ID FROM #tmpID
END
Sign up to request clarification or add additional context in comments.

2 Comments

Not a day goes by without learning something new. +10 if I could but I've used up my votes for today...
@Lieven - I frequently find myself trying to think like the T-SQL compiler. The trick is to say to oneself "what's the stupidest thing I could do here?"
1

You don't need to use a temporary table. This should be enough:

CREATE PROCEDURE QOTD (@source INT) 
AS  
BEGIN 
 IF @source = 1
    SELECT ID FROM tbl1  
 ELSE 
    SELECT ID  FROM tbl2  
END 

Comments

-2

There already exists a temporary table #tmpID in your database. Try using this before your procedure.

Drop table #tmpID

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.