我有一个sql脚本来创建一个新的数据库,我需要在安装我们的产品时创建它。为此,我需要使用c#触发脚本。 DB是sql-server 2005 express。 Plz帮助......
sql脚本如下:
USE [master]
GO
/****** Object: Database [Jai] Script Date: 02/12/2010 11:01:25 ******/
CREATE DATABASE [Jai] ON PRIMARY
( NAME = N'Jai', FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\DATA\Jai.mdf' , SIZE = 3072KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB )
LOG ON
( NAME = N'Jai_log', FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\DATA\Jai_log.ldf' , SIZE = 1024KB , MAXSIZE = 2048GB , FILEGROWTH = 10%)
COLLATE SQL_Latin1_General_CP1_CI_AS
GO
EXEC dbo.sp_dbcmptlevel @dbname=N'Jai', @new_cmptlevel=90
GO
IF (1 = FULLTEXTSERVICEPROPERTY('IsFullTextInstalled'))
begin
EXEC [Jai].[dbo].[sp_fulltext_database] @action = 'disable'
end
GO
ALTER DATABASE [Jai] SET ANSI_NULL_DEFAULT OFF
GO
ALTER DATABASE [Jai] SET ANSI_NULLS OFF
GO
ALTER DATABASE [Jai] SET ANSI_PADDING OFF
GO
ALTER DATABASE [Jai] SET ANSI_WARNINGS OFF
GO
ALTER DATABASE [Jai] SET ARITHABORT OFF
GO
ALTER DATABASE [Jai] SET AUTO_CLOSE OFF
GO
ALTER DATABASE [Jai] SET AUTO_CREATE_STATISTICS ON
GO
ALTER DATABASE [Jai] SET AUTO_SHRINK OFF
GO
ALTER DATABASE [Jai] SET AUTO_UPDATE_STATISTICS ON
GO
ALTER DATABASE [Jai] SET CURSOR_CLOSE_ON_COMMIT OFF
GO
ALTER DATABASE [Jai] SET CURSOR_DEFAULT GLOBAL
GO
ALTER DATABASE [Jai] SET CONCAT_NULL_YIELDS_NULL OFF
GO
ALTER DATABASE [Jai] SET NUMERIC_ROUNDABORT OFF
GO
ALTER DATABASE [Jai] SET QUOTED_IDENTIFIER OFF
GO
ALTER DATABASE [Jai] SET RECURSIVE_TRIGGERS OFF
GO
ALTER DATABASE [Jai] SET ENABLE_BROKER
GO
ALTER DATABASE [Jai] SET AUTO_UPDATE_STATISTICS_ASYNC OFF
GO
ALTER DATABASE [Jai] SET DATE_CORRELATION_OPTIMIZATION OFF
GO
ALTER DATABASE [Jai] SET TRUSTWORTHY OFF
GO
ALTER DATABASE [Jai] SET ALLOW_SNAPSHOT_ISOLATION OFF
GO
ALTER DATABASE [Jai] SET PARAMETERIZATION SIMPLE
GO
ALTER DATABASE [Jai] SET READ_WRITE
GO
ALTER DATABASE [Jai] SET RECOVERY FULL
GO
ALTER DATABASE [Jai] SET MULTI_USER
GO
ALTER DATABASE [Jai] SET PAGE_VERIFY CHECKSUM
GO
ALTER DATABASE [Jai] SET DB_CHAINING OFF
答案 0 :(得分:9)
Here是来自MSDN的帖子,解释了如何使用SMO执行此操作:
using System.Data.SqlClient;
using System.IO;
using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string sqlConnectionString = "Data Source=(local);Initial Catalog=AdventureWorks;Integrated Security=True";
FileInfo file = new FileInfo("C:\\myscript.sql");
string script = file.OpenText().ReadToEnd();
SqlConnection conn = new SqlConnection(sqlConnectionString);
Server server = new Server(new ServerConnection(conn));
server.ConnectionContext.ExecuteNonQuery(script);
}
}
}
答案 1 :(得分:7)
当我需要运行包含GO语句的sql脚本时,我通常会将整个文件读入一个字符串,并使用GO作为分隔符将其拆分为字符串数组。
然后我连接到数据库并按顺序运行每个语句。
这很简单,效果很好。只需确保在运行所有语句时保持数据库连接处于打开状态。您也可以考虑在交易中全部运行它们。
答案 2 :(得分:5)