我的项目解决方案中有一个文件夹,其中包含需要执行的多个.sql文件。现在我可以一个接一个地运行它们,但这需要一段时间。
有没有办法有效地做到这一点?
答案 0 :(得分:2)
我通常将.sql文件放在目录中并运行如下的批处理文件:
@ECHO OFF
for /f %%a in (ServerNames.txt) do (
setlocal
echo Accessing %%a...
for %%d in (*.sql) do sqlcmd -S%%a -E -i%%d
endlocal
)
这将使用您的Windows身份验证在当前目录中执行所有 .sql脚本。 “ServerNames.txt”包含您要在其上执行.sql文件的每个服务器的所有名称。
您可以使用-S参数
将其修改为仅在服务器上执行可以找到有关sqlcmd的其他参数和信息here
答案 1 :(得分:1)
Here你有办法做到这一点
CREATE TABLE ##SQLFiles ( SQLFileName VARCHAR(2000))
GO
INSERT INTO ##SQLFiles
EXECUTE master.dbo.xp_cmdshell 'dir /b "C:\SQL Scripts\*.sql"'
GO
DECLARE cFiles CURSOR LOCAL FOR
SELECT DISTINCT [SQLFileName]
FROM ##SQLFiles
WHERE [SQLFileName] IS NOT NULL AND
[SQLFileName] != 'NULL'
ORDER BY [SQLFileName]
DECLARE @vFileName VARCHAR(200)
DECLARE @vSQLStmt VARCHAR(4000)
OPEN cFiles
FETCH NEXT FROM cFiles INTO @vFileName
WHILE @@FETCH_STATUS = 0
BEGIN
-- The following SET command must be on a single line or else an error will be generated.
-- It is split in this script for readability purposes.
SET @vSQLStmt = 'master.dbo.xp_cmdshell ''osql -S Server Name -U User Name -P Password
-d Database Name -i "C:\SQL Scripts\' + @vFileName + '"'''
EXECUTE (@vSQLStmt)
FETCH NEXT FROM cFiles INTO @vFileName
END
CLOSE cFiles
DEALLOCATE cFiles
GO
DROP TABLE ##SQLFiles
GO
答案 2 :(得分:1)
使用dotnet的方式
protected void btn_Click(object sender, EventArgs e)
{
string strdbname=txtdbname.text;
string strCreatecmd = "create database " + strdbname + "";
SqlCommand cmd = new SqlCommand(strCreatecmd, con1);
con1.Open();
cmd.ExecuteNonQuery();
con1.Close();
// Code to execute sql script ie(create tables/storedprocedure/views on ms sqlserver)
//generatescript.sql is sql script generated and placed under Add_data folder in my application
FileInfo file = new FileInfo(Server.MapPath("App_Data\\generatescript.sql"));
string strscript = file.OpenText().ReadToEnd();
string strupdatescript = strscript.Replace("[databaseOldnameWhileSriptgenerate]", strdbname);
Server server = new Server(new ServerConnection(con1));
server.ConnectionContext.ExecuteNonQuery(strupdatescript);
con1.Close();
}
http://satindersinght.blogspot.in/2012/01/how-to-execute-sql-script-file-in.html
答案 3 :(得分:0)
有很多方法......
如果我考虑一下,可能会想到更多的想法。 What have you tried?你有什么技能?你是开发人员吗? .NET,Java,VBScript,Perl等......给出一个特定的答案有点难以继续下去。