在SSMS中,当我点击数据库“Tasks - > Generate Scripts”时,我得到一个输出脚本。
如何使用非图形工具执行相同操作?
答案 0 :(得分:7)
图形工具只是实际实现脚本的SMO类的包装器,如Scripter类。有一个示例使用MSDN中的SMO编写数据库中所有表的脚本:Scripting:
//Connect to the local, default instance of SQL Server.
{
Server srv = default(Server);
srv = new Server();
//Reference the AdventureWorks database.
Database db = default(Database);
db = srv.Databases("AdventureWorks");
//Define a Scripter object and set the required scripting options.
Scripter scrp = default(Scripter);
scrp = new Scripter(srv);
scrp.Options.ScriptDrops = false;
scrp.Options.WithDependencies = true;
//Iterate through the tables in database and script each one. Display the script.
//Note that the StringCollection type needs the System.Collections.Specialized namespace to be included.
Table tb = default(Table);
Urn[] smoObjects = new Urn[2];
foreach ( tb in db.Tables) {
smoObjects = new Urn[1];
smoObjects(0) = tb.Urn;
if (tb.IsSystemObject == false) {
StringCollection sc = default(StringCollection);
sc = scrp.Script(smoObjects);
string st = null;
foreach ( st in sc) {
Console.WriteLine(st);
}
}
}
}
还有更多示例如何在其他各种网站上使用它。
答案 1 :(得分:2)
您可以使用powershell执行此操作。脚本表的示例。 http://www.simple-talk.com/sql/sql-tools/using-powershell-to-generate-table-creation-scripts/我猜测应该可以扩展其他类型的数据库对象。
编辑只是注意到标题说的是数据和架构。我不知道从命令行执行此操作的任何免费内容。如果您购买正确的版本,可以从命令行自动执行Redgate SQL Compare Suite,或者您可以编写应用程序/电源shell脚本来执行此操作。
答案 2 :(得分:2)
对于数据,您可以使用名为bcp
的批量导出实用程序,它允许您将SQL Server表中的数据转储到文件中,例如CSV文件或制表符分隔文件。
我不知道任何SQL Server提供的实用程序会像SQL Server Management Studio那样使用INSERT语句创建SQL脚本。
答案 3 :(得分:1)
您可以使用SQL Server发布向导编写架构和数据。这可以从命令行完成。版本1.4是你想要它与2008版本的Visual Studio以及SQL Server 2008捆绑在一起的版本。你可以在Program Files / Microsoft SQL server / 90 / Tools / Publishing / 1.4 / SqlPubWiz中找到它我相信它也是一个项目在CodePlex上。
输入SQlPubWiz /?查看命令行选项
答案 4 :(得分:1)
我编写了一个名为SchemaZen的开源命令行实用程序来执行此操作。它比管理工作室的脚本快得多,它的输出更适合版本控制。它支持脚本化架构和数据。
生成脚本运行:
schemazen.exe script --server localhost --database db --scriptDir c:\somedir
然后从脚本运行:
重新创建数据库schemazen.exe create --server localhost --database db --scriptDir c:\somedir
答案 5 :(得分:1)
微软上周发布了一款名为mssql-scripter的新工具。它是SSMS中“Generate Scripts”向导的命令行版本。该工具是基于Python的开源命令行工具,您可以找到官方声明here。本质上,脚本编写器允许您将数据库/数据库对象的T-SQL脚本(DDL和DML)生成为.sql文件。这是一个快速使用示例,可以帮助您入门:
$ pip install mssql-scripter
# script the database schema and data piped to a file.
$ mssql-scripter -S localhost -d AdventureWorks -U sa --schema-and-data > ./adventureworks.sql
更多用法示例在我们的GitHub页面上: https://github.com/Microsoft/sql-xplat-cli/blob/dev/doc/usage_guide.md
答案 6 :(得分:0)
准备在http://exportsqlscript.codeplex.com/使用免费的开源命令行架构导出工具。
命令行驱动实用程序,用于将MS SQL对象导出为适合数据库创建和修订控制的脚本文件。 使用与SQL Server 2000,SQL Server 2005,SQL Server 2008和SQL Server 2008 R2兼容的2008R2服务器管理对象(SMO)。
必须从Windows Installer 4.5安装.NET Framework 3.5,SQL Server 2008 R2 Feature Pack和共享管理对象以及系统CLR类型才能使其正常运行。
SQL Server 2005的工作导出命令示例:
ExportSQLScript.exe . dldb /ot:Tree /xt:UserDefinedTableTypes
答案 7 :(得分:0)
您可以下载powershell脚本
https://gallery.technet.microsoft.com/SCRIPTING-DB-DB-OBJECTS-DB-81bba072
powershell脚本将编写db,db对象,db权限, sql登录,sql权限,sql作业,sql链接服务器,sql邮件, sql server触发器
$path = "E:\pruthvi\pruthvi\"
$servername="SRVBLRDBATST98\MSSQLSERVER1"
$query=@"
set nocount off
IF OBJECT_ID(N'tempdb..##temp1') IS NOT NULL
DROP TABLE ##temp1
create table ##temp1(query varchar(1000))
insert into ##temp1
select 'use '+db_name() +';'
insert into ##temp1
select 'go'
/*creating database roles*/
insert into ##temp1
select 'if DATABASE_PRINCIPAL_ID('''+name+''') is null exec sp_addrole '''+name+''';' from sysusers
where issqlrole = 1 and (sid is not null and sid <> 0x0)
/*creating application roles*/
insert into ##temp1
select 'if DATABASE_PRINCIPAL_ID('+char(39)+name+char(39)+')
is null CREATE APPLICATION ROLE ['+name+'] WITH DEFAULT_SCHEMA = ['+
default_schema_name+'], Password='+char(39)+'Pass$w0rd123'+char(39)+' ;'
from sys.database_principals
where type_desc='APPLICATION_ROLE'
insert into ##temp1
select
case
when state_desc='GRANT_WITH_GRANT_OPTION'
then
substring (state_desc,0,6)+' '+permission_name+' to '+'['+USER_NAME(grantee_principal_id)+']'+' WITH
GRANT OPTION ;'
else
state_desc+' '+permission_name+' to '+'['+USER_NAME(grantee_principal_id)+']'+' ;'
END
from sys.database_permissions
where class=0 and USER_NAME(grantee_principal_id) not in ('dbo','guest','sys','information_schema')
insert into ##temp1
select
case
when state_desc='GRANT_WITH_GRANT_OPTION'
then
substring (state_desc,0,6)+' '+permission_name+' on '+OBJECT_SCHEMA_NAME(major_id)+'.'+OBJECT_NAME
(major_id)
+' to '+'['+USER_NAME(grantee_principal_id)+']'+' with grant option ;'
else
state_desc+' '+permission_name+' on '+OBJECT_SCHEMA_NAME(major_id)+'.'+OBJECT_NAME(major_id)
+' to '+'['+USER_NAME(grantee_principal_id)+']'+' ;'
end
from sys.database_permissions where class=1 and USER_NAME(grantee_principal_id) not in ('public');
insert into ##temp1
select
case
when state_desc='GRANT_WITH_GRANT_OPTION'
then
substring (state_desc,0,6)+' '+permission_name+' ON schema::['+sa.name+
'] to ['+user_name(dp.grantee_principal_id)+'] with grant option ;'
else
state_desc+' '+permission_name+' ON schema::['+sa.name+
'] to ['+user_name(dp.grantee_principal_id)+'] ;'
COLLATE LATIN1_General_CI_AS
end
from sys.database_permissions dp inner join sys.schemas sa on
sa.schema_id = dp.major_id where dp.class=3
insert into ##temp1
select
case
when state_desc='GRANT_WITH_GRANT_OPTION'
then
substring (state_desc,0,6)+' '+permission_name+' ON APPLICATION ROLE::['+sa.name+
'] to ['+user_name(dp.grantee_principal_id)+'] with grant option ;'
else
state_desc+' '+permission_name+' ON APPLICATION ROLE::['+sa.name+
'] to ['+user_name(dp.grantee_principal_id)+'] ;'
COLLATE LATIN1_General_CI_AS
end
from sys.database_permissions dp inner join sys.database_principals sa on
sa.principal_id = dp.major_id where dp.class=4 and sa.type='A'
insert into ##temp1
select
case
when state_desc='GRANT_WITH_GRANT_OPTION'
then
substring (state_desc,0,6)+' '+permission_name+' ON ROLE::['+sa.name+
'] to ['+user_name(dp.grantee_principal_id)+'] with grant option ;'
else
state_desc+' '+permission_name+' ON ROLE::['+sa.name+
'] to ['+user_name(dp.grantee_principal_id)+'] ;'
COLLATE LATIN1_General_CI_AS
end
from sys.database_permissions dp inner join
sys.database_principals sa on sa.principal_id = dp.major_id
where dp.class=4 and sa.type='R'
insert into ##temp1
select
case
when state_desc='GRANT_WITH_GRANT_OPTION'
then
substring (state_desc,0,6)+' '+permission_name+' ON ASSEMBLY::['+sa.name+
'] to ['+user_name(dp.grantee_principal_id)+'] with grant option ;'
else
state_desc+' '+permission_name+' ON ASSEMBLY::['+sa.name+
'] to ['+user_name(dp.grantee_principal_id)+'] ;'
COLLATE LATIN1_General_CI_AS
end
from sys.database_permissions dp inner join sys.assemblies sa on
sa.assembly_id = dp.major_id
where dp.class=5
insert into ##temp1
select
case
when state_desc='GRANT_WITH_GRANT_OPTION'
then
substring (state_desc,0,6)+' '+permission_name+' ON type::['
+SCHEMA_NAME(schema_id)+'].['+sa.name+
'] to ['+user_name(dp.grantee_principal_id)+'] with grant option ;'
else
state_desc+' '+permission_name+' ON type::['
+SCHEMA_NAME(schema_id)+'].['+sa.name+
'] to ['+user_name(dp.grantee_principal_id)+'] ;'
COLLATE LATIN1_General_CI_AS
end
from sys.database_permissions dp inner join sys.types sa on
sa.user_type_id = dp.major_id
where dp.class=6
insert into ##temp1
select
case
when state_desc='GRANT_WITH_GRANT_OPTION'
then
substring (state_desc,0,6)+' '+permission_name+' ON XML SCHEMA COLLECTION::['+
SCHEMA_NAME(SCHEMA_ID)+'].['+sa.name+'] to ['+user_name(dp.grantee_principal_id)+'] with grant option ;'
else
state_desc+' '+permission_name+' ON XML SCHEMA COLLECTION::['+
SCHEMA_NAME(SCHEMA_ID)+'].['+sa.name+'] to ['+user_name(dp.grantee_principal_id)+'];'
COLLATE LATIN1_General_CI_AS
end
from sys.database_permissions dp inner join sys.xml_schema_collections sa on
sa.xml_collection_id = dp.major_id
where dp.class=10
insert into ##temp1
select
case
when state_desc='GRANT_WITH_GRANT_OPTION'
then
substring (state_desc,0,6)+' '+permission_name+' ON message type::['+sa.name+
'] to ['+user_name(dp.grantee_principal_id)+'] with grant option ;'
else
state_desc+' '+permission_name+' ON message type::['+sa.name+
'] to ['+user_name(dp.grantee_principal_id)+'] ;'
COLLATE LATIN1_General_CI_AS
end
from sys.database_permissions dp inner join sys.service_message_types sa on
sa.message_type_id = dp.major_id
where dp.class=15
insert into ##temp1
select
case
when state_desc='GRANT_WITH_GRANT_OPTION'
then
substring (state_desc,0,6)+' '+permission_name+' ON contract::['+sa.name+
'] to ['+user_name(dp.grantee_principal_id)+'] with grant option ;'
else
state_desc+' '+permission_name+' ON contract::['+sa.name+
'] to ['+user_name(dp.grantee_principal_id)+'] ;'
COLLATE LATIN1_General_CI_AS
end
from sys.database_permissions dp inner join sys.service_contracts sa on
sa.service_contract_id = dp.major_id
where dp.class=16
insert into ##temp1
select
case
when state_desc='GRANT_WITH_GRANT_OPTION'
then
substring (state_desc,0,6)+' '+permission_name+' ON SERVICE::['+sa.name+
'] to ['+user_name(dp.grantee_principal_id)+'] with grant option ;'
else
state_desc+' '+permission_name+' ON SERVICE::['+sa.name+
'] to ['+user_name(dp.grantee_principal_id)+'] ;'
COLLATE LATIN1_General_CI_AS
end
from sys.database_permissions dp inner join sys.services sa on
sa.service_id = dp.major_id
where dp.class=17
insert into ##temp1
select
case
when state_desc='GRANT_WITH_GRANT_OPTION'
then
substring (state_desc,0,6)+' '+permission_name+' ON REMOTE SERVICE BINDING::['+sa.name+
'] to ['+user_name(dp.grantee_principal_id)+'] with grant option ;'
else
state_desc+' '+permission_name+' ON REMOTE SERVICE BINDING::['+sa.name+
'] to ['+user_name(dp.grantee_principal_id)+'] ;'
COLLATE LATIN1_General_CI_AS
end
from sys.database_permissions dp inner join sys.remote_service_bindings sa on
sa.remote_service_binding_id = dp.major_id
where dp.class=18
insert into ##temp1
select
case
when state_desc='GRANT_WITH_GRANT_OPTION'
then
substring (state_desc,0,6)+' '+permission_name+' ON route::['+sa.name+
'] to ['+user_name(dp.grantee_principal_id)+'] with grant option ;'
else
state_desc+' '+permission_name+' ON route::['+sa.name+
'] to ['+user_name(dp.grantee_principal_id)+'] ;'
COLLATE LATIN1_General_CI_AS
end
from sys.database_permissions dp inner join sys.routes sa on
sa.route_id = dp.major_id
where dp.class=19
insert into ##temp1
select
case
when state_desc='GRANT_WITH_GRANT_OPTION'
then
substring (state_desc,0,6)+' '+permission_name+' ON FULLTEXT CATALOG::['+sa.name+
'] to ['+user_name(dp.grantee_principal_id)+'] with grant option ;'
else
state_desc+' '+permission_name+' ON FULLTEXT CATALOG::['+sa.name+
'] to ['+user_name(dp.grantee_principal_id)+'] ;'
COLLATE LATIN1_General_CI_AS
end
from sys.database_permissions dp inner join sys.fulltext_catalogs sa on
sa.fulltext_catalog_id = dp.major_id
where dp.class=23
insert into ##temp1
select
case
when state_desc='GRANT_WITH_GRANT_OPTION'
then
substring (state_desc,0,6)+' '+permission_name+' ON SYMMETRIC KEY::['+sa.name+
'] to ['+user_name(dp.grantee_principal_id)+'] with grant option ;'
else
state_desc+' '+permission_name+' ON SYMMETRIC KEY::['+sa.name+
'] to ['+user_name(dp.grantee_principal_id)+'] ;'
COLLATE LATIN1_General_CI_AS
end
from sys.database_permissions dp inner join sys.symmetric_keys sa on
sa.symmetric_key_id = dp.major_id
where dp.class=24
insert into ##temp1
select
case
when state_desc='GRANT_WITH_GRANT_OPTION'
then
substring (state_desc,0,6)+' '+permission_name+' ON certificate::['+sa.name+
'] to ['+user_name(dp.grantee_principal_id)+'] with grant option ;'
else
state_desc+' '+permission_name+' ON certificate::['+sa.name+
'] to ['+user_name(dp.grantee_principal_id)+'] ;'
COLLATE LATIN1_General_CI_AS
end
from sys.database_permissions dp inner join sys.certificates sa on
sa.certificate_id = dp.major_id
where dp.class=25
insert into ##temp1
select
case
when state_desc='GRANT_WITH_GRANT_OPTION'
then
substring (state_desc,0,6)+' '+permission_name+' ON ASYMMETRIC KEY::['+sa.name+
'] to ['+user_name(dp.grantee_principal_id)+'] with grant option ;'
else
state_desc+' '+permission_name+' ON ASYMMETRIC KEY::['+sa.name+
'] to ['+user_name(dp.grantee_principal_id)+'] ;'
COLLATE LATIN1_General_CI_AS
end
from sys.database_permissions dp inner join sys.asymmetric_keys sa on
sa.asymmetric_key_id = dp.major_id
where dp.class=26
insert into ##temp1
select 'exec sp_addrolemember ''' +p.NAME+''','+'['+m.NAME+']'+' ;'
FROM sys.database_role_members rm
JOIN sys.database_principals p
ON rm.role_principal_id = p.principal_id
JOIN sys.database_principals m
ON rm.member_principal_id = m.principal_id
where m.name not like 'dbo';
select * from ##temp1
"@
$loginscript=@"
IF ((SELECT convert(int,substring(@@VERSION,21,5)))<2008)
begin
set nocount on
declare @table table (query varchar(max))
insert into @table
select 'CREATE LOGIN '+QUOTENAME(name)+' FROM WINDOWS WITH DEFAULT_DATABASE='+QUOTENAME(default_database_name)+' ;'
from sys.server_principals where type in('U','G')
insert into @table
select 'CREATE LOGIN ' + QUOTENAME(name)+
' WITH PASSWORD =' +CONVERT(varchar(max), LOGINPROPERTY(name, 'PasswordHash'),1 )+' HASHED ,SID='+'0x' + CAST('' as XML).value('xs:hexBinary(sql:column("sid"))', 'varchar(MAX)')+', default_database=['+default_database_name+'],'+
case when is_policy_checked=0 then 'CHECK_POLICY = OFF' when is_policy_checked=1 then 'CHECK_POLICY = ON ' end+
case when is_expiration_checked=0 then ' , CHECK_EXPIRATION = OFF ' when is_policy_checked=1 then ', CHECK_EXPIRATION = ON' end+
'; '+case when is_disabled=1 then 'ALTER LOGIN ['+name+ '] DISABLE;' when is_disabled=0 then ' ' end
from sys.sql_logins where name not like '%##%' and name not like '%sa%'
select * from @table
end
else
begin
set nocount on
declare @table1 table (query varchar(max))
insert into @table1
select 'CREATE LOGIN '+QUOTENAME(name)+' FROM WINDOWS WITH DEFAULT_DATABASE='+QUOTENAME(default_database_name)+' ;'
from sys.server_principals where type in('U','G')
insert into @table1
select 'CREATE LOGIN ' + QUOTENAME(name)+
' WITH PASSWORD =' +CONVERT(varchar(max), LOGINPROPERTY(name, 'PasswordHash'),1 )+' HASHED ,SID='+CONVERT(varchar(max), sid, 1)+', default_database=['+default_database_name+'],'+
case when is_policy_checked=0 then 'CHECK_POLICY = OFF' when is_policy_checked=1 then 'CHECK_POLICY = ON ' end+
case when is_expiration_checked=0 then ' , CHECK_EXPIRATION = OFF ' when is_policy_checked=1 then ', CHECK_EXPIRATION = ON' end+
'; '+case when is_disabled=1 then 'ALTER LOGIN ['+name+ '] DISABLE;' when is_disabled=0 then ' ' end
from sys.sql_logins where name not like '%##%' and name not like '%sa%'
select * from @table1
end
"@
$serverperm=@"
set nocount on
IF OBJECT_ID(N'tempdb..##servrole') IS NOT NULL
DROP TABLE ##servrole
CREATE TABLE ##servrole (query varchar(1000))
insert into ##servrole
select 'use master;'
insert into ##servrole
select ' exec sp_addsrvrolemember '''+m.name+''','+p.name+';' FROM sys.server_role_members rm
JOIN sys.server_principals p
ON rm.role_principal_id = p.principal_id
JOIN sys.server_principals m
ON rm.member_principal_id = m.principal_id
where m.name not in ('sa','dbo','entity owner','information_schema','sys','public');
insert into ##servrole
select
case when sp.state_desc='GRANT_WITH_GRANT_OPTION' then
substring (state_desc,0,6)+' '+permission_name+' to ['+srp.name+'] with grant option ;'
else
state_desc+' '+permission_name+' to ['+srp.name+'] ;'
end
from sys.server_permissions sp
join sys.server_principals srp on sp.grantee_principal_id=srp.principal_id
where srp.name not like '%##%' and
srp.name not in ('sa','dbo','entity owner','information_schema','sys')
and sp.type not in ('COSQ','CO');
select query as ' ' from ##servrole where query is not null;
go
drop table ##servrole
go
"@
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO')
$s = new-object ('Microsoft.SqlServer.Management.Smo.Server') $servername
$dbs=$s.Databases
foreach ($db in $dbs)
{
$dbname = "$db".replace("[","").replace("]","")
$dbpath = "$path"
$db.script()| out-file $path$dbname.txt
foreach ($tables in $db.tables)
{
$tables.script() |out-file $path$dbname.txt -append
foreach ($index in $tables.Indexes)
{
$index.script() |out-file $path$dbname.txt -append
}
}
bcp "use $db ;select definition from sys.sql_modules " queryout $path$dbname"1".txt -c -t -T -S $servername
gc $path$dbname.txt,$path$dbname"1".txt | out-file $path$dbname"2".txt
$myTable=Invoke-Sqlcmd -Query $query -ServerInstance $servername -database $dbname
$myTable|Format-Table -AutoSize|Out-String -Width 8192 |out-file $path$dbname"2".txt -append
rm $path$dbname.txt,$path$dbname"1".txt
}
$srv=new-object "Microsoft.SqlServer.management.smo.server" $servername
$srv.JobServer.Jobs|%{$_.script()}|out-file $path"agentjobs".txt
$srv.LinkedServers|%{$_.script()}|out-file $path"linkedservers".txt
$srv.backupdevices|%{$_.script()}|out-file $path"backupdevices".txt
$srv.mail|%{$_.script()}|out-file $path"mail".txt
$srv.triggers|%{$_.script()}|out-file $path"servertriggers".txt
$myTable=Invoke-Sqlcmd -Query $loginscript -ServerInstance $servername -database master
$myTable|Format-Table -AutoSize|Out-String -Width 8192 |out-file $path"serverlogins".txt -append
$servperm=Invoke-Sqlcmd -Query $serverperm -ServerInstance $servername -database master
$servperm|Format-Table -AutoSize|Out-String -Width 8192 |out-file $path"serverpermission".txt -append