November 8, 2006 at 2:43 am
Can you use if exists in this fashon:
if exists table
select * from table
else.....
end if
I have tried a few different ways of doing this but i cant get it to work.
Thanks all
November 8, 2006 at 3:27 am
The correct syntax is look like
if exists
(select * from dbo.sysobjects where id = object_id(N'[table1]')
and OBJECTPROPERTY(id, N'IsUserTable') = 1)
select * from table1
else
--Print Table1 does'nt exists
end if
Hope this will slove your problem
cheers
November 8, 2006 at 4:15 am
No, it won't work.
You could use dynamic SQL to do this, but I would remind you that shema is an essential part of relational database. And if you at run time don't know if the table exists then you don't have database at all. It's just set of files placed by mistake into some tables.
_____________
Code for TallyGenerator
November 8, 2006 at 5:06 am
Well... it is a bit strange to use test on existence before select, but it is very often used with DDL (IF EXISTS ... DROP TABLE and then CREATE TABLE with the same name). I've seen it so many times, that I consider existence test being "normal". Is it really that bad, Sergiy? I would agree with you if the question would be how to use such test with a variable table name, but this is not the case (at least as I understand the question).
ijaz, END IF is not used in SQL. The block has to be enclosed in BEGIN ... END.
For temporary tables, you can use this:
IF object_id('tempdb..#table1') IS NOT NULL
DROP TABLE #table1
November 8, 2006 at 2:10 pm
You could query the system table sysobjects (SQL Server 2K) or sys.objects (SQL Server 2K5):
If Exists(Select * From sysobjects Where type = 'U' and name = 'table')
Select * From table
Else...
November 8, 2006 at 2:29 pm
Give it a try.
It works with CREATE/DROP objects, it's OK for temporary objects, but it will fail on compilation time if there is a SELECT from not existing static object.
To compile the code optimiser needs internal addresses for all referenced objects. CREATE/DROP deals with sysobjects, so it will proceed. But attempt to include SELECT from not existing object will not allow to compile SP.
It will not even start execution and will not get to the point IF NOT EXISTS.
_____________
Code for TallyGenerator
November 8, 2006 at 8:53 pm
One test is worth a thousand words... run the following... do note that the AUTHOR table does NOT exist in PUBS...
USE PUBS
GO
IF OBJECT_ID('dbo.Author') IS NOT NULL --No such table
BEGIN
SELECT * FROM dbo.Author
END
IF OBJECT_ID('dbo.Authors') IS NOT NULL
BEGIN
SELECT * FROM dbo.Authors
END
Anybody see any errors in the run? Me neither... and works fine as a stored proc, as well.
--Jeff Moden
Change is inevitable... Change for the better is not.
November 9, 2006 at 6:36 am
So what are you trying to accomplish with this? Maybe we could point you in another direction if we had more details!
Viewing 8 posts - 1 through 7 (of 7 total)
You must be logged in to reply to this topic. Login to reply