I am trying move this command to C# Process:
SQLCMD.EXE -S InstanceName
USE [master]
GO
CREATE DATABASE [Ek] ON
( FILENAME = N'C:\Program Files\Microsoft SQL
Server\MSSQL15.MSSQLSERVER\MSSQL\DATA\Ek_Primary.mdf' ),
( FILENAME = N'C:\Program Files\Microsoft SQL
Server\MSSQL15.MSSQLSERVER\MSSQL\DATA\Ek_Primary.ldf' )
FOR ATTACH ;
GO
EXIT
I have:
try
{
Process p = CreateProcess();
p.StartInfo.FileName = @"C:\Program Files\Microsoft SQL Server\Client SDK\ODBC\170\Tools\Binn\SQLCMD.EXE";
p.StartInfo.Arguments = "-S InstanceName" + "\n" +
"USE [master]" + "\n" +
"GO" + "\n" +
"CREATE DATABASE [Ek] ON" + "\n" +
"( FILENAME = N'C:\\Program Files\\Microsoft SQL Server\\MSSQL15.MSSQLSERVER\\MSSQL\\DATA\\Ek_Primary.mdf' )," + "\n" +
"( FILENAME = N'C:\\Program Files\\Microsoft SQL Server\\MSSQL15.MSSQLSERVER\\MSSQL\\DATA\\Ek_Primary.ldf' )" + "\n" +
"FOR ATTACH ;" + "\n" +
"GO" + "\n" +
"EXIT" + "\n";
Console.WriteLine(p.StartInfo.Arguments);
p.Start();
var output = p.StandardOutput.ReadToEnd();
var err = p.StandardError.ReadToEnd();
Console.WriteLine("O: " + output);
Console.WriteLine("E: " + err);
}
catch (Exception e) { Console.WriteLine(e.Message); ; }
It return err = Unexpected argument. Enter '-?' for help.
I was trying set FileName on cmd.exe and move path to Arguments. But it waits forever for a response and does not exit p.StandardOutput.ReadToEnd ();
I was trying send each line of code individually, but also without success.
And I trying with /C on start p.StartInfo.Argument but it does not change anything.
Thanks to Selvin suggestion. I made it by:
string sqlConnectionString = @"Integrated Security=SSPI;Persist Security Info=False;Data Source=InstanceName";
string script = File.ReadAllText(@"../../sql.sql");
Microsoft.Data.SqlClient.SqlConnection conn = new Microsoft.Data.SqlClient.SqlConnection(sqlConnectionString);
Server server = new Server(new ServerConnection(conn));
server.ConnectionContext.ExecuteNonQuery(script);
where in sql.sql I added all my sql line.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.