在 ExecuteSqlRaw() 中接近 'GO' 的语法不正确



我正在尝试对LocalDb实例运行一些原始SQL:

dbContext.Database.Migrate();
dbContext.Database.ExecuteSqlRaw(sql);

从这个文件中读取sql:

/****** Object:  StoredProcedure [dbo].[aspnet_AnyDataInTables]    Script Date: 02/02/2021 22:11:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[aspnet_AnyDataInTables]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[aspnet_AnyDataInTables] AS' 
END
GO
ALTER PROCEDURE [dbo].[aspnet_AnyDataInTables]
@TablesToCheck int
AS
BEGIN
-- Check Membership table if (@TablesToCheck & 1) is set
IF ((@TablesToCheck & 1) <> 0 AND
(EXISTS (SELECT name FROM sysobjects WHERE (name = N'vw_aspnet_MembershipUsers') AND (type = 'V'))))
BEGIN
IF (EXISTS(SELECT TOP 1 UserId FROM dbo.aspnet_Membership))
BEGIN
SELECT N'aspnet_Membership'
RETURN
END
END
[...abbreviated...]

该脚本所做的全部工作是创建SQL Membership提供程序所需的存储过程。我从一个现有的数据库生成了这个脚本。

当从SQL Server Management Studio对同一个LocalDb实例运行时,这个脚本运行良好,但是当从代码中运行时,它抛出一个SqlException:

Incorrect syntax near 'GO'.
Incorrect syntax near 'GO'.
Incorrect syntax near 'GO'.
Must declare the scalar variable "@TablesToCheck".
Incorrect syntax near ')'.
Must declare the scalar variable "@TablesToCheck".
Incorrect syntax near ')'.
Must declare the scalar variable "@TablesToCheck".
Incorrect syntax near ')'.
Must declare the scalar variable "@TablesToCheck".
Incorrect syntax near ')'.
Must declare the scalar variable "@TablesToCheck".
Incorrect syntax near ')'.
Must declare the scalar variable "@TablesToCheck".
Incorrect syntax near 'GO'.
Incorrect syntax near 'GO'.
Incorrect syntax near 'GO'.
Incorrect syntax near 'GO'.
Must declare the scalar variable "@ApplicationId".
Must declare the scalar variable "@ApplicationId".
Must declare the scalar variable "@ApplicationId".
Incorrect syntax near the keyword 'with'. If this statement is a common table expression, an xmlnamespaces clause or a change tracking context clause, the previous statement must be terminated with a semicolon.
Must declare the scalar variable "@ApplicationId".
Must declare the scalar variable "@ApplicationId".
Must declare the scalar variable "@ApplicationId".
Incorrect syntax near 'GO'.
Incorrect syntax near 'GO'.
Incorrect syntax near 'GO'.
Incorrect syntax near 'GO'.
Must declare the scalar variable "@Feature".
[...abbreviated...]

我如何让它运行没有错误?

使用EF Core 3.1.3.

正如@Lamu指出的那样,GO不是Transact-SQL操作符。因此,显而易见的解决方案是将脚本分成更小的批:

string[] batches = sql.Split(new [] {"nGO"}, StringSplitOptions.None);
foreach (string batch in batches)
{
dbContext.Database.ExecuteSqlRaw(batch);
}

最新更新