65.9K
CodeProject 正在变化。 阅读更多。
Home

SQL 脚本执行器或读取器执行 Microsoft SQL 脚本

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.10/5 (7投票s)

2007年9月10日

CPOL
viewsIcon

29981

SQL 脚本执行器或读取器执行已经生成的脚本。只需更改脚本所在的路径即可。

引言

本文介绍一个 SQL 脚本读取器或执行器,它执行已经生成的脚本。只需更改脚本所在的路径即可。

背景

如果您有一些生成的脚本并想执行它们,请修改这些脚本。

Using the Code

执行已经生成的脚本。只需更改脚本所在的路径即可。如果您有多个脚本并想同时执行它们,则可以使用包含脚本目录路径和脚本名称的数组。

using System;
using System.Data.SqlClient;
using System.IO;
using System.Data;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Nmo;
using Microsoft.SqlServer.Management.Smo.Agent;

namespace SQL_ScriptReader
{
    public class scriptReader
    {
	public scriptReader()
	{ 
   	    //SQL script reader default constructor
	}
	// the below method requires only connection string 
	// this is understood that script has no error and has same column 
         // name and data type
	public void ReadScript(string ConnectionString)
	{
	    string sqlConnectionString = ConnectionString;
	    //Directory where the script reside
		
	    FileInfo file = new FileInfo(@"d:\script.txt");
	    // this string opens and reads the script from start to end
	    // if your script is too long then use any collection or any other thing 
             //which u want and use method of .Tostring()
	    string script = file.OpenText().ReadToEnd();
	    //below code reside in following name spaces be default Microsoft just 
             //include them
	
	    /* using Microsoft.SqlServer.Management.Smo;
	    using Microsoft.SqlServer.Management.Nmo;
	    using Microsoft.SqlServer.Management.Smo.Agent;
	    */
	    Server server = new Server();
	    server.ConnectionContext.ConnectionString = sqlConnectionString;
			
	    server.ConnectionContext.ExecuteNonQuery(script);
	    // 
	    // if your script has key word like \n and 
             // you want to not add in your data base 
             // then use ExecutionTypes.QuotedIdentifierOn
	    // otherwise off

	    /*server.ConnectionContext.ExecuteNonQuery
               (script,Microsoft.SqlServer.Management.Common.ExecutionTypes.
               QuotedIdentifierOn); 
             */ 
	}
    }
}

我没有使用 try catch 块。您可以将其用于提高代码效率。

历史

  • 2007 年 9 月 10 日:初始发布
© . All rights reserved.