using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.SqlServer.Management.Common;//需添加microsoft.sqlserver.connectioninfo.dll的引用
using Microsoft.SqlServer.Management;//
using Microsoft.SqlServer.Management.Smo;//在microsoft.sqlserver.smo.dll中
using Microsoft.SqlServer.Management.Smo.RegisteredServers;//Microsoft.SqlServer.SmoExtended
using Microsoft.SqlServer.Management.Smo.Broker;
using Microsoft.SqlServer.Management.Smo.Agent;
using Microsoft.SqlServer.Management.Smo.SqlEnum;
using Microsoft.SqlServer.Management.Smo.Mail;
using Microsoft.SqlServer.Management.Smo.Internal;
using System.IO;
using System.Data.SqlClient;
using System.Text;
using System.Text.RegularExpressions; ////引用位置: C:\Program Files\Microsoft SQL Server\100\SDK\Assemblies\ /// <summary>
/// 涂聚文 2017-06-02
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button2_Click(object sender, EventArgs e)
{
//Connect to the local, default instance of SQL Server.
Microsoft.SqlServer.Management.Common.ServerConnection conn = new ServerConnection(@"GEOVI-BD87B6B9C\GEOVINDU", "geovindu", "888888");
Server srv = new Server(conn);
//Reference the AdventureWorks2012 database.
Database db = srv.Databases["du"]; //Define a UserDefinedFunction object variable by supplying the parent database and the name arguments in the constructor.
UserDefinedFunction udf = new UserDefinedFunction(db, "IsOWeek"); //Set the TextMode property to false and then set the other properties.
udf.TextMode = false;
udf.DataType = DataType.Int;
udf.ExecutionContext = ExecutionContext.Caller;
udf.FunctionType = UserDefinedFunctionType.Scalar;
udf.ImplementationType = ImplementationType.TransactSql; //Add a parameter. UserDefinedFunctionParameter par = new UserDefinedFunctionParameter(udf, "@DATE", DataType.DateTime);
udf.Parameters.Add(par); //Set the TextBody property to define the user-defined function.
udf.TextBody = "BEGIN DECLARE @ISOweek int SET @ISOweek= DATEPART(wk,@DATE)+1 -DATEPART(wk,CAST(DATEPART(yy,@DATE) as CHAR(4))+'0104') IF (@ISOweek=0) SET @ISOweek=dbo.ISOweek(CAST(DATEPART(yy,@DATE)-1 AS CHAR(4))+'12'+ CAST(24+DATEPART(DAY,@DATE) AS CHAR(2)))+1 IF ((DATEPART(mm,@DATE)=12) AND ((DATEPART(dd,@DATE)-DATEPART(dw,@DATE))>= 28)) SET @ISOweek=1 RETURN(@ISOweek) END;"; //Create the user-defined function on the instance of SQL Server.
udf.Create(); //Remove the user-defined function.
// udf.Drop();
}
/// <summary>
/// 涂聚文 2017-06-02
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button3_Click(object sender, EventArgs e)
{
try
{ //涂聚文 2017-06-02
Microsoft.SqlServer.Management.Common.ServerConnection serverconn = new ServerConnection(@"GEOVI-BD87B6B9C\GEOVINDU", "geovindu", "888888");
string sqlConnectionString = @"Data Source=GEOVI-BD87B6B9C\GEOVINDU;Initial Catalog=Du;User ID=Geovin Du;Password=888888";
//1.有报错问题
//FileInfo file = new FileInfo("fu.sql");
//string script = file.OpenText().ReadToEnd();
//script = script.Replace("\t", " ").Replace("\n", " ");
//SqlConnection conn = new SqlConnection(sqlConnectionString);
//Server server = new Server(serverconn);//new ServerConnection(conn)
//Database db = server.Databases["du"];
//server.ConnectionContext.ExecuteNonQuery(script);//出问题 SqlConnection conn = new SqlConnection(sqlConnectionString);
conn.Open();
string script = File.ReadAllText("fu.sql"); // split script on GO command
IEnumerable<string> commandStrings = Regex.Split(script, @"^\s*GO\s*$", RegexOptions.Multiline | RegexOptions.IgnoreCase);
foreach (string commandString in commandStrings)
{
if (commandString.Trim() != "")
{
new SqlCommand(commandString, conn).ExecuteNonQuery();
}
}
MessageBox.Show("Database updated successfully."); }
catch(Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
} /// <summary>
/// Run an .sql script trough sqlcmd.
/// </summary>
/// <param name="fileName">the .sql script</param>
/// <param name="machineName">The name of the server.</param>
/// <param name="databaseName">The name of the database to connect to.</param>
/// <param name="trustedConnection">Use a trusted connection.</param>
/// <param name="args">The arguments passed to the sql script.</param>
public void RunSqlScript(string fileName, string machineName, string databaseName, bool trustedConnection, string[] args)
{
// simple checks
if (!Path.GetExtension(fileName).Equals(".sql", StringComparison.InvariantCulture))
throw new Exception("The file doesn't end with .sql."); // check for used arguments
foreach (var shortArg in new[] { "S", "d", "E", "i" })
{
var tmpArg = args.SingleOrDefault(a => a.StartsWith(string.Format("-{0}", shortArg), StringComparison.InvariantCulture));
if (tmpArg != null)
throw new ArgumentException(string.Format("Cannot pass -{0} argument to sqlcmd for a second time.", shortArg));
} // check the params for trusted connection.
var userArg = args.SingleOrDefault(a => a.StartsWith("-U", StringComparison.InvariantCulture));
var passwordArg = args.SingleOrDefault(a => a.StartsWith("-P", StringComparison.InvariantCulture));
if (trustedConnection)
{
if (userArg != null)
throw new ArgumentException("Cannot pass -H argument when trustedConnection is used.");
if (passwordArg != null)
throw new ArgumentException("Cannot pass -P argument when trustedConnection is used.");
}
else
{
if (userArg == null)
throw new ArgumentException("Exspecting username(-H) argument when trustedConnection is not used.");
if (passwordArg == null)
throw new ArgumentException("Exspecting password(-P) argument when trustedConnection is not used.");
} // set the working directory. (can be needed with ouputfile)
// TODO: Test if the above statement is correct
var tmpDirectory = Directory.GetCurrentDirectory();
var directory = Path.IsPathRooted(fileName) ? Path.GetDirectoryName(fileName) : Path.Combine(fileName);//this.ProjectRoot
var file = Path.GetFileName(fileName);
Directory.SetCurrentDirectory(directory); // create cmd line
var cmd = string.Format(string.Format("SQLCMD -S {0} -d {1} -i \"{2}\"", machineName, databaseName, file));
foreach (var argument in args.Where(a => a.StartsWith("-", StringComparison.InvariantCultureIgnoreCase)))
cmd += " " + argument;
if (trustedConnection)
cmd += " -E"; // create the process
var process = new System.Diagnostics.Process();
process.StartInfo.FileName = "cmd";
process.StartInfo.CreateNoWindow = true;
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardInput = true; // start the application
process.Start();
process.StandardInput.WriteLine("@ECHO OFF");
process.StandardInput.WriteLine(string.Format("cd {0}", directory));
process.StandardInput.WriteLine(cmd);
process.StandardInput.WriteLine("EXIT");
process.StandardInput.Flush();
process.WaitForExit(); // write the output to my debug folder and restore the current directory
// Debug.Write(process.StandardOutput.ReadToEnd());
Directory.SetCurrentDirectory(tmpDirectory);
} // public void Restore(OdbcConnection sqlcon, string DatabaseFullPath, string backUpPath)
// {
// using (sqlcon)
// {
// string UseMaster = "USE master";
// OdbcCommand UseMasterCommand = new OdbcCommand(UseMaster, sqlcon);
// UseMasterCommand.ExecuteNonQuery();
// // The below query will rollback any transaction which is running on that database and brings SQL Server database in a single user mode.
// string Alter1 = @"ALTER DATABASE
// [" + DatabaseFullPath + "] SET Single_User WITH Rollback Immediate";
// OdbcCommand Alter1Cmd = new OdbcCommand(Alter1, sqlcon);
// Alter1Cmd.ExecuteNonQuery();
// // The below query will restore database file from disk where backup was taken ....
// string Restore = @"RESTORE DATABASE
// [" + DatabaseFullPath + "] FROM DISK = N'" +
// backUpPath + @"' WITH FILE = 1, NOUNLOAD, STATS = 10";
// OdbcCommand RestoreCmd = new OdbcCommand(Restore, sqlcon);
// RestoreCmd.ExecuteNonQuery();
// // the below query change the database back to multiuser
// string Alter2 = @"ALTER DATABASE
// [" + DatabaseFullPath + "] SET Multi_User";
// OdbcCommand Alter2Cmd = new OdbcCommand(Alter2, sqlcon);
// Alter2Cmd.ExecuteNonQuery();
// Cursor.Current = Cursors.Default;
// }
// }

  https://www.codeproject.com/Tips/873677/SQL-Server-Database-Backup-and-Restore-in-Csharp

https://www.codeproject.com/Articles/162684/SMO-Tutorial-of-n-Scripting

https://www.codeproject.com/articles/31826/sql-server-authentication-using-smo

https://stackoverflow.com/questions/650098/how-to-execute-an-sql-script-file-using-c-sharp

https://social.msdn.microsoft.com/Forums/en-US/43e8bc3a-1132-453b-b950-09427e970f31/run-a-sql-script-file-in-c?forum=adodotnetdataproviders

VS 2010 报错:

+ $exception {"混合模式程序集是针对“v2.0.50727”版的运行时生成的,在没有配置其他信息的情况下,无法在 4.0 运行时中加载该程序集。":null} System.Exception {System.IO.FileLoadException}

App.config 配置:

1.一种方式

<startup  useLegacyV2RuntimeActivationPolicy="true">
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
<supportedRuntime version="v2.0.50727"/>
</startup>

2.二种方式

<startup useLegacyV2RuntimeActivationPolicy="true">
<supportedRuntime version="v4.0"/>
</startup>

  

 

csharp:SMO run sql script的更多相关文章

  1. How to Enable Trace or Debug for APIs executed as SQL Script Outside of the Applications ?

    In this Document   Goal   Solution   1: How do you enable trace for an API when executed from a SQL ...

  2. 可重复执行的SQL Script

    问题 在工作中偶尔会遇到这样的问题:SQL script重复执行时会报错. 理想的状态下,SQL script跑一遍就够了,是不会重复执行的,但是实际情况往往很复杂. 比如Dev同学在开发时在A环境把 ...

  3. MySQL5.7: sql script demo

    -- MyISAM Foreign Keys显示不了外键,MyISAM此为5.0 以下版本使用 InnoDB 为5.0以上版本使用 drop table IF EXISTS city; CREATE ...

  4. SQLite: sql script demo

    如果有成熟的架构,如何根据数据库关系的表.视图等,进行代码生成架构?减少写代码的时间? -- 考虑主键外键 -- create database geovindu; use geovindu; --2 ...

  5. How to import .sql script

    How to import .sql script 1.Export .sql from pl/sql developer you can reference to other document in ...

  6. npm link & run npm script

    npm link & run npm script https://blog.csdn.net/juhaotian/article/details/78672390 npm link命令可以将 ...

  7. Run bash script as daemon

    linux - Run bash script as daemon - Stack Overflow https://stackoverflow.com/questions/19233529/run- ...

  8. The fileSyncDll.ps1 is not digitally signed. You cannot run this script on the current system.

    https://www.opentechguides.com/how-to/article/powershell/105/powershel-security-error.html Unblockin ...

  9. doris: shell invoke .sql script for doris and passing values for parameters in sql script.

    1. background in most cases, we want to execute sql script  in doris  routinely. using azkaban, to l ...

随机推荐

  1. Go Code Review Comments 译文(截止2018年7月27日)

    持续更新中- 原文最新链接 https://github.com/golang/go/wiki/CodeReviewComments/5a40ba36d388ff1b8b2dd4c1c3fe820b8 ...

  2. linux下报错bash: service: command not found

    在linux下操作的时候经常会遇到,bash: service: command not found这个错误,以前在网上找了,照着弄了,也没细看原因,今天又碰到这个问题,就顺便研究一下. 1.通常这种 ...

  3. sublime text 3中安装ctags支持函数跳转,安装convertToUtf8支持中文步骤[工具篇]

    sublime text x是个很不错的编辑器,但是各种插件都需要自己安装,有时也有点不方便,尤其是自己还不不知道怎么安装的时候.开发中经常用到的,函数跳转,就是一个比较难安装的东西,记录如下(系统为 ...

  4. Java匹马行天下之JavaSE核心技术——面向对象

    面向对象 注: 看此篇时强烈建议有一定的面向对象思想基础,有一定的基础后先翻到下面看第九条:      9.面向对象: 从未封装→封装→继承→多态→抽象类→接口的代码演变 按这个逻辑去看,,哪有不理解 ...

  5. [源码]Delphi源码免杀之函数动态调用 实现免杀的下载者

    [免杀]Delphi源码免杀之函数动态调用 实现免杀的下载者 2013-12-30 23:44:21         来源:K8拉登哥哥's Blog   自己编译这份代码看看 过N多杀软  没什么技 ...

  6. [P4921] 情侣?给我烧了!

    回顾一下错排公式 错排问题: 设n位错排数为D[n].考虑元素1的位置,设置为k(有n-1中 ):在考虑元素k的位置, 若为1,则转换为n-2位的错排:否则,视元素k为元素1(不能放在位置1),转换为 ...

  7. Java获取URL中的顶级域名domain的工具类

    方式一: import java.net.MalformedURLException; import java.net.URL; import java.util.Arrays; import jav ...

  8. 2.WF 4.5 流程引擎设计思路

    本文主要给大家分享下基于WF 4.5框架的流程引擎设计思路 1.流程启动时的数据写入EventMsgPP对象中,ObjectAssemblyType记录流程启动时需要的类型,ObjectContent ...

  9. SpringBoot2.0源码分析(一):SpringBoot简单分析

    SpringBoot2.0简单介绍:SpringBoot2.0应用(一):SpringBoot2.0简单介绍 本系列将从源码角度谈谈SpringBoot2.0. 先来看一个简单的例子 @SpringB ...

  10. 逆向知识之CS1.6辅助/外挂专题.1.实现CS1.6主武器副武器无限子弹

    逆向知识之CS辅助/外挂专题.1.实现CS主武器副武器无限子弹 PS: 相信大家CS1.6这类的FPS应该玩过.现在我们通过外挂手法.讲解逆向的本质.以及应用. 关于CS1.6的下载.网络百度下载即可 ...