Non riesco a eseguire SQL che crea un database utilizzando un oggetto DbCommand. Che cosa sto facendo di sbagliato? Ecco il mio codice:Come eseguire SQL con commenti e istruzioni GO utilizzando SqlConnection?
DbConnection connection; // initialized and opened elsewhere
DbCommand cmd = connection.CreateCommand();
cmd.CommandText = sql;
cmd.ExecuteNonQuery();
Ecco l'errore:
The query syntax is not valid., near term '/', line 1, column 2. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Data.EntitySqlException: The query syntax is not valid., near term '/', line 1, column 2.
Ecco la prima parte del file. L'eccezione viene generata per quanto riguarda solo i commenti sulla prima riga:
/****** Object: Table [dbo].[User] Script Date: 10/08/2009 12:14:29 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[User](
[Id] [int] IDENTITY(1,1) NOT NULL,
[FirstName] [nvarchar](50) NULL,
[LastName] [nvarchar](50) NULL,
[EmailAddress] [nvarchar](100) NULL,
CONSTRAINT [PK_User] 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
Questo stesso script SQL eseguito bene da SQL Management Studio Express (in realtà tale applicazione ha generato questo script!). È solo la visualizzazione delle query di Server Explorer di Visual Studio e dal mio codice che sembra fallire.
Nota: GO non è un comando SQL, si tratta di un comando per lo strumento client (come OSQL, Query Analyzer, o in questo caso SMSS.) Per rompere lo script in lotti separati" ". Ogni lotto è una chiamata separata al server. –
Possibile duplicato di [Esegui uno script SQL di grandi dimensioni (con comandi GO)] (http://stackoverflow.com/questions/40814/execute-a-large-sql-script-with-go-commands) –