I’m working with SQL 2005, and have the following code:
DECLARE @exist4 INT
IF ( SELECT COUNT(*) existe
FROM sysobjects obj
WHERE obj.name = 'table4'
) > 0
BEGIN
SET @exist4 = 1
END
ELSE
BEGIN
SET @exist4 = 0
END
/*now if table4 exist i need add to my query but if i do something as it
i got next error
Invalid object name 'table4'.*/
IF ( @exist4 = 0 )
BEGIN
SELECT [table].col1 ,
[table].col2 ,
[table].col3 ,
[table].colN
FROM [table] ,
table2 ,
table3
WHERE [table].id = table1.id
AND table3.id = table2.id
END
ELSE
BEGIN
SELECT [table].col1 ,
[table].col2 ,
[table].col3 ,
[table].colN
FROM [table] ,
table2 ,
table3 ,
table4
WHERE [table].id = table2.id
AND table3.id = table2.id
AND table4.id = table3.id
END
This code returns an error when Table4 does not exist. How can I get this query to work?
What is happening is that table4 does not exist at the time the query is parsed. That means you can’t run the query.
What you need to do is to delay the parsing of that part of the query until you know that table4 exists.
You can do this by putting the query in a string then running the stored procedure sp_excutesql. Something like this:
The part of the query that references table4 is only available as a string when the whole query is parsed the first time, so the parser sees just a string, not the reference to the various tables. When you run sp_executesql the string is then parsed and run. And since you put this inside your IF block it will only parse and run when it knows that table4 exists.