In searching for an answer to this question, I found this popular post on StackOverflow. Unfortunately, it doesn't work completely. The question is this:
Is there a way to check for existence of a table (or another object) before performing modifications (e.g. INSERT
)? The before mentioned post suggests this:
IF (EXISTS (SELECT *
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'dbo'
AND TABLE_NAME = 'questionableTable'))
BEGIN
INSERT INTO dbo.questionableTable VALUES ('success!');
END
Error: Invalid object name 'dbo.questionableTable'.
The problem with this is that SQL Server fails when it parses the INSERT
statement, stating that dbo.questionableTable
doesn't exist. The previous INFORMATION_SCHEMA
check doesn't seem to affect it.
Is there a way to write this kind of query? For SQL Server, in particular. But I would also like to see similar operations for other database systems, if such things exist.
The motivation behind this question is because we have multiple databases which contain subsets of each others' tables. What I would like is to have a single script that can be applied to all databases, and which only modified the tables that exist there (and doesn't error upon execution).