sql - Test if Table Exists in Linked Server (Server Name is a Parameter) -
i need test if table exists in linked server, linked server parameter (it has be), that's why i'm using exec method. tried many ways didn't succeed.
declare @linkedservername varchar(50) declare @ds varchar(50) declare @username varchar(50) declare @pswd varchar(12) declare @tableexists int set @ds = 'test\testdb' set @linkedservername = 'linkedserverautoadddrop' set @username = 'ua' set @pswd = 'pass' set @tableexists = 0 if not exists(select * sys.servers name = @linkedservername) begin exec sp_addlinkedserver @server=@linkedservername, @srvproduct='', @provider='sqlncli', @datasrc=@ds exec sp_addlinkedsrvlogin @linkedservername, n'false', null, @username, @pswd exec sp_serveroption @server=@linkedservername, @optname='rpc', @optvalue='true' exec sp_serveroption @server=@linkedservername, @optname='rpc out', @optvalue='true' end exec('if (exists (select * openquery([' + @linkedservername + '], ''select * linkeddb.information_schema.tables table_name = ''''tablename''''''))) begin exec (''set ' + @tableexists + ' = 1'') end') if (@tableexists = 1) begin exec('insert ...') end
i use sp_executesql
along output parameter this:
declare @sql nvarchar(max) = '' declare @tableexists bit; set @sql = 'select @tableexists = case when tableexists = 0 0 else 1 end openquery(' + quotename(@linkedservername) + ', ''select tableexists = count(*) linkeddb.information_schema.tables table_name = ''''tablename'''''');'; execute sp_executesql @sql, n'@tableexists bit output', @tableexists out; if (@tableexists = 1) begin -- end;
Comments
Post a Comment