sql - Dynamic Query for record fetch -


i having scenario this

databse 1 inserting table :

id    person     1     john 

before inserting record have make sure person exists handeled in other db

database 2;

person   ou john     1 shyam    2 

database 3:

person   ou  ram      5 

....

once record exists have insert same record in database. if nothing exists pop error person entered invalid.

i have tried code

 select *,         row_number() over(order name)  'r'         #temp    sys.databases    database_id not in (1,2,3,4,db_id(db_name()))  declare @int =1  declare @person varchar(100) = person inserting (nolock) declare @dbname varchar(max) declare @sql nvarchar(max)  while (@i <= (select max(r) #temp)) begin  set @dbname = (select name #temp r = @i)  set @sql = 'if exists (select 1 '''+ @dbname+'''..person person = +'''@person'''+)' execute sp_executesql @sql set @i = (select max(r) #temp))+2 else set @i = @i+1 end  if @i> (select max(r)+1 #temp) begin set @sql = 'insert ''' +@dbname+'''..person select id,person person' execute sp_executesql @sql end else raiserror('no record esxists.',16,1) 

but still unable insert record if record exists. 1 can make query better or suggestions welcome.

you can use synonyms in database in order use person table database 2 , database 3.

create synonym [dbo].[person2] [server2].[database2].[dbo].[person] create synonym [dbo].[person3] [server3].[database3].[dbo].[person] 

after create synonyms person table on database2 , database3, person2 , person3 behave such person table on database1 , can insert, update , delete rows them without problem.


Comments

Popular posts from this blog

google api - Incomplete response from Gmail API threads.list -

Installing Android SQLite Asset Helper -

Qt Creator - Searching files with Locator including folder -