Check if Table Exists in external linked database

混江龙づ霸主 提交于 2019-12-12 02:12:34

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!