copying table with data from different database in Microsoft SQL Server -
copying table with data from different database in Microsoft SQL Server -
i writing store procedure info migration. in there, need re-create table , whole info other database current database's temp table. but, database name come parameter. , need process copied data. but, not know how create dynamic database name.
create procedure [dbo].[mgrt] @dbname varchar(50) begin set nocount on; if object_id('tempdb..#tmpch') not null drop table #tmpch; select * #tmpch mddx.dbo.ch order mdate,mtime declare @count int = 0 declare @currow int = 0 select @count = count(*) #tmpch while @currow <= @count begin declare @lastdate nvarchar(10) = '-' set @lastdate = (select top 1 to_date ch order syskey desc) if @lastdate = '' or @lastdate null begin set @lastdate = '-' print @lastdate end insert ch(syskey,curcode,curdesc,cursymbol,currate,from_date,to_date,userid,username) (select @currow,curcode,curdesc,cursymbol,currate,@lastdate,mdate,'admin','administrator' (select *,row_number() over(order mdate,mtime) rowno #tmpch) tmp rowno = @currow) set @currow = @currow + 1 end end
i need utilize @dbname instead of mddx in getting data.
thank you!
you need utilize dynamic query, follows;
create procedure [dbo].[mgrt] @dbname varchar(50) begin set nocount on; declare ssql varchar(200) if object_id('tempdb..#tmpch') not null drop table #tmpch; ssql = 'select * #tmpch @dbname.dbo.ch order mdate,mtime' exec (ssql) declare @count int = 0 declare @currow int = 0 select @count = count(*) #tmpch while @currow <= @count begin declare @lastdate nvarchar(10) = '-' set @lastdate = (select top 1 to_date ch order syskey desc) if @lastdate = '' or @lastdate null begin set @lastdate = '-' print @lastdate end insert ch(syskey,curcode,curdesc,cursymbol,currate,from_date,to_date,userid,username) (select @currow,curcode,curdesc,cursymbol,currate,@lastdate,mdate,'admin','administrator' (select *,row_number() over(order mdate,mtime) rowno #tmpch) tmp rowno = @currow) set @currow = @currow + 1 end end
sql-server
Comments
Post a Comment