I have a SQL script that I've been working on making more flexible. I need it to be able to insert rows into tables in one DB then create a table and insert rows in another DB on the same server. I can each of these things in two different scripts of course, but I'm trying to figure out how to do it all in one. Here is an example of what I've tried:
use firmTriad
create table #TempTable (IssueId nvarchar(300),[SQL] nvarchar(300),FirmID varchar(255),[Table] varchar(255),SecurityDelete varchar(255)
,SecurityKeep varchar(255))
declare @IssueID nvarchar(300),@SQL nvarchar(300),@FirmID varchar(255),@SecurityCUSIPdelete varchar(255),@SecurityCUSIPkeep varchar(255)
set @SecurityCUSIPkeep = 'AET133A20'
set @SecurityCUSIPdelete = 'AEXVA0559'
set @FirmID = 'firmTriad'
set @IssueID = 'RQST00002652426'
set @IssueID = 'tblSecurity_MSReference_' + @IssueID
insert into #TempTable (IssueId,FirmID,SecurityDelete,SecurityKeep)
select @IssueID,@FirmID,@SecurityCUSIPdelete,@SecurityCUSIPkeep
use PSBackup
select * from #TempTable
declare @Table varchar(255), @PSTable varchar(255)
set @PSTable = 'tblSecurity_MSReference_' + @IssueID
set @Table = @FirmID + '.dbo.' + left(@Table,len(@Table)-16)
print (@FirmID)
set @SQL = 'create table ' + @IssueID + '([RecID],[SecurityID],[MSCUSIP],[LastUpdateDT]
,Issue_Key,Issue_Backup_Date,Issue_Backup_Len)'
exec @SQL
insert into sys. (@firmID + '.dbo.tblSecurity_MSReference') --firmTriad.dbo.tblSecurity_MSReference
select [RecID],[SecurityID],[MSCUSIP],[LastUpdateDT],Issue_Key,Issue_Backup_Date,Issue_Backup_Len
from @Table
where [SecurityID] in(select RecID from firmTriad.dbo.tblSecurity where CUSIP in(@SecurityCUSIPdelete,@SecurityCUSIPkeep))
I can't figure out how to get the variables to carry over between the two use db sections.