问题
So I'm creating a script where I"m linking a database that is in another server.
Using OBJECT_ID I want to check whether a table exists in the external linked database like so:
IF OBJECT_ID('[10.0.48.139].[DBNAME].[dbo].tblRating', 'U') IS NOT NULL
BEGIN
SET @Sql = N'
INSERT INTO tblRating
( fldSubDivisionID ,
fldClientName ,
fldAddress ,
fldCountryID ,
fldComments ,
fldCreatedDate ,
fldCreatedBy ,
fldModifiedDate ,
fldModifiedBy
)
SELECT * FROM ' + @SourceDB + '.tblRating';
EXECUTE sp_executesql @Sql;
END
ELSE
PRINT 'Table [tblRating] Not Found in Source Database'
Even though the table exists in [10.0.48.139].[DBNAME].[dbo] for some reason it always returns null. I don't think OBJECT_ID likes it when you put an Serverlocation or ip in there.
回答1:
You could query the INFORMATION_SCHEMA
of the linked database to accomplish this. First, though, you'd have to create a view on the linked DB since it cannot be queried directly like so:
CREATE VIEW vwInformationSchemaTables AS SELECT * FROM INFORMATION_SCHEMA.TABLES
Then you can query from the linked database like so:
IF EXISTS(SELECT 1 FROM [10.0.48.139].[DBNAME].dbo.vwInformationSchemaTables WHERE TABLE_NAME='tblRating')
BEGIN
--table exists
END
来源:https://stackoverflow.com/questions/22182437/check-if-table-exists-in-external-linked-database