我試圖創建一個方法來在SQL Server數據庫上運行.sql文件。使用C#在SQL Server上執行sql文件
的代碼,我是:
SqlConnection dbCon = new SqlConnection(connstr);
FileInfo file = new FileInfo(Server.MapPath("~/Installer/JobTraksDB.sql"));
StreamReader fileRead = file.OpenText();
string script = fileRead.ReadToEnd();
fileRead.Close();
SqlCommand command = new SqlCommand(script, dbCon);
try
{
dbCon.Open();
command.ExecuteNonQuery();
dbCon.Close();
}
catch (Exception ex)
{
throw new Exception("Failed to Update the Database, check your Permissions.");
}
但我不斷收到關於 「附近關鍵字 'GO' 不正確的語法」 錯誤 我的SQL文件開頭是這樣的:(從SQL Management Studio中生成)
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Job_Types](
[ID] [int] IDENTITY(1,1) NOT NULL,
[Name] [varchar](50) NOT NULL,
CONSTRAINT [PK_JobTypes] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
我應該如何執行這個腳本?
我可以看到一個bug:假設我有一個名爲'sp'的過程,腳本是'「sp」'。 'commandText.Substring(0,3)'會拋出一個'IndexOutOfRangeException'。 –
@Mehrdad:是的,常見的錯誤,假設String.Substring(0,xxx)與VB函數Left(xxx)完全相同。 :-) –
@WowtaH:除此之外,做得很好。 :-) –