T SQL Information schema?

database information-schema sql sqlbulkcopy tsql

Question

We have a lot of data and to save time on making backups I have been tasked with creating a copy of the current database which only contains specified company codes/companies.

I have been told to research into TSQL scripts, information schemas and bulk copies.Im just wondering what the best route is to go down and how to make a start I do have the latest database copy locally.

The script would work by

Allow us at the top to specify name of new database and a list of company codes or ids from company table.

And create a new database and copy over only the data that is relevant

Accepted Answer

Probably not even close to the best way... but 1 of 100 ways you can do it.

declare @databasename nvarchar(100) = 'roflcopter'
, @destination = 'myschema.mytable'
declare @companylist nvarchar(max) = (select stuff( select ',' +convert(nvarchar(5),companyid) from companytable where database = @databasename),1,1,'')

declare @query nvarchar(max) 
= N'use ['+@databasename+']
insert into '+@destination+' /* maybe add dynamic columns here */
select /*same dynamic columns */
from mytable /*or another variable*/
where companyid in('''+@companylist+''')
'
exec (@query)

add your other variables and such to declare destination, future database name (if creating) and anything you want... dynamic sql can be slow, cumbersome and does reconnect. Might want to check the sp_executesql for differences between exec () and executesql

there are a ton of system procedures... ones that find FKs, column names, data types, pks... you can complicate it by building dynamically creating your current schema using (no help from me here) those system procedures, C# to easily 'generate scripts' and execute them.

May also be in the wrong direction you were thinking of.



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why