I've only been able to see this work with a stored procedure and I can't figure out the syntax. I basically have some external system calling a SQL query and I want to verify the table exists first using code similar to this:
if (EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'OrderUpdates'))
BEGIN
--return 1 or 0 if it exists or doesn't exist
END
I can't get the return statement to work properly.
SELECT CAST(COUNT(*) AS BIT) -- Should be unique to give 0 or 1 as result
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'dbo'
AND TABLE_NAME = 'OrderUpdates'
-- Not sure if you want views or not:
AND TABLE_TYPE = 'BASE TABLE'
I don't understand quite what you are getting at - RETURN is only valid in a stored procedure or function.
If you want the same thing in a set (because the caller is expecting a rowset), then something like this can work:
SELECT 1 AS DoesItExist
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'dbo'
AND TABLE_NAME = 'OrderUpdates'
UNION ALL
SELECT 0
WHERE NOT EXISTS (SELECT *
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'dbo'
AND TABLE_NAME = 'OrderUpdates')
SQL Server has a table named 'tables', which contains the list of tables in your database. So following code should help:
CREATE PROCEDURE DoesTableExist(@table VARCHAR(50), @exists BIT OUTPUT)
AS
BEGIN
IF EXISTS(SELECT * FROM sys.tables WHERE name = @table)
SET @exists = 1
ELSE
SET @exists = 0
RETURN @exists
END
You could do something like this:
USE SomeDatabase;
IF OBJECT_ID('YourTable', 'U') IS NOT NULL
BEGIN
SELECT 1
END ELSE BEGIN
SELECT 0
END
If you're looking for a type other than a User Table, you can change the 'U' in OBJECT_ID
to the correct value as determined by the types listed in sys.objects