I et en essayant de créer une méthode pour exécuter un fichier .sql sur une base de données SQL Server.Exécuter le fichier SQL sur un serveur SQL en utilisant C#
Le code que j'ai est:
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.");
}
Mais je continue à obtenir des erreurs sur "syntaxe incorrecte près de mot-clé 'GO'" Mon fichier SQL commence comme ceci: (généré à partir de 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
Comment dois-je exécuter ce script?
Je peux voir un bug: Supposons que j'ai une procédure nommée 'sp' et que le script est' 'sp ''. 'commandText.Substring (0, 3)' lancera une 'IndexOutOfRangeException'. –
@Mehrdad: Oui, erreur commune, en supposant que String.Substring (0, xxx) fonctionne exactement comme la fonction VB Left (xxx). :-) –
@WowtaH: A part ça, c'est bien fait. :-) –