在 SSMS 中,当我单击数据库“Tasks -> Generate Scripts”时,我得到一个输出脚本。
我如何使用非图形工具做同样的事情?
在 SSMS 中,当我单击数据库“Tasks -> Generate Scripts”时,我得到一个输出脚本。
我如何使用非图形工具做同样的事情?
图形工具只是实际实现脚本的 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);
}
}
}
}
还有更多示例如何在其他各种站点上使用它。
对于数据,您可以使用名为的批量导出实用程序bcp
,该实用程序允许您将数据从 SQL Server 表转储到文件中,例如 CSV 文件或制表符分隔的文件。
我不知道任何 SQL Server 提供的实用程序会像 SQL Server Management Studio 那样使用 INSERT 语句创建 SQL 脚本。
您可以使用 powershell 来执行此操作。这里是脚本表的示例。http://www.simple-talk.com/sql/sql-tools/using-powershell-to-generate-table-creation-scripts/我猜应该可以扩展其他类型的数据库对象。
编辑刚刚注意到标题表示数据和模式。我不知道从命令行执行此操作的任何免费内容。如果您购买了正确的版本,或者您可以编写应用程序/电源 shell 脚本来执行此操作,Redgate SQL Compare Suite 可以从命令行自动执行。
我编写了一个名为SchemaZen的开源命令行实用程序来执行此操作。它比管理工作室的脚本要快得多,而且它的输出对版本控制更友好。它支持脚本模式和数据。
要生成脚本运行:
schemazen.exe 脚本 --server localhost --database db --scriptDir c:\somedir
然后从脚本运行重新创建数据库:
schemazen.exe 创建 --server localhost --database db --scriptDir c:\somedir
您可以使用 SQL Server 发布向导编写架构和数据脚本。这可以从命令行完成。1.4 版是您希望它与 Visual Studio 2008 版以及 SQL Server 2008 捆绑在一起的版本。您可以在 Program Files/Microsoft SQL server/90/Tools/Publishing/1.4/SqlPubWiz 中找到它我相信它也是一个项目在 CodePlex 上。
输入 SQlPubWiz /? 查看命令行选项
微软上周发布了一个名为 mssql-scripter 的新工具。它是 SSMS 中“生成脚本”向导的命令行版本。该工具是一个基于 Python 的开源命令行工具,您可以在此处找到官方公告。本质上,脚本程序允许您为数据库/数据库对象生成 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
在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 功能包中的系统 CLR 类型的共享管理对象才能使其工作。
SQL Server 2005 的工作导出命令示例:
ExportSQLScript.exe . dldb /ot:Tree /xt:UserDefinedTableTypes
你可以下载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