更新时间:2023-10-15 21:10:52
-详细$ c>输出仅显示语句摘要。如果在SQL Server Management Studio中手动运行命令,则在两个语句之间需要
GO
:
The -Verbose
output just shows a summary of statements. If you run your command manually in SQL Server Management Studio then you need a GO
between the two statements:
ALTER TABLE [dbo].[Posts] ADD [Abstract] [nvarchar](max)
GO
UPDATE dbo.Posts SET Abstract = LEFT(Content, 100) WHERE Abstract IS NULL
快速解决方案是执行以下操作:
The quick fix is to do something like:
^ {:b *} {{INSERT | UPDATE | SELECT | DELETE}。+}
(这会找到任何CRUD语句) \1GO\n\1\2\n
(保留缩进,并在任何CRUD语句之前添加 GO
)^{:b*}{{INSERT|UPDATE|SELECT|DELETE}.+}
(this finds any CRUD statements)\1GO\n\1\2\n
(keep the indents, and add GO
before any CRUD statements)但是请注意,-详细
没有提供您想要的输出,您需要输出从-脚本
,否则您将丢失 __ MigrationHistory
历史记录表的插入数据,这可能会导致应用程序抛出运行时出现错误(有关详细信息,请参见下文)。
But, note that -Verbose
doesn't give you the output you want, you need the output from -Script
, or you will be missing the inserted data for the __MigrationHistory
history table which could cause your application to throw an error when it runs (see below for details).
详细信息
您对以下 MSDN代码优先迁移页面上的信息的评论很有趣。该页面实际上声明了(在获取SQL脚本 下)
Your comment below about the information on the MSDN Code First Migrations page is interesting. The page actually states (under the section "Getting a SQL Script")
运行Update-Database命令但这一次指定–Script标志
Run the Update-Database command but this time specify the –Script flag
如果执行此操作,您将看到类似以下内容的
If you do this you will see something like:
ALTER TABLE [dbo].[Posts] ADD [Abstract] [nvarchar](max)
UPDATE dbo.Posts SET Abstract = LEFT(Content, 100) WHERE Abstract IS NULL
INSERT INTO [__MigrationHistory] ([MigrationId], [Model], [ProductVersion]) VALUES ( ...
INSERT
很重要-这就是您的应用程序中的EF如何知道它正在使用最新的数据库版本(因此运行,而不是向您显示错误。)但是,它仍然缺少GO命令。因此,SQL Server尝试将3行作为一个批处理进行编译,并失败。
The INSERT
is important - this is how your EF in your application will know it is using the latest db version (and will therefore run instead of showing you an error). But, it is still missing that GO command. SQL server therefore tries to compile the 3 lines as a single batch and fails.
添加所需的 GO
语句后,您仍然可以通过将其包围来在单个事务中运行它h:
After adding the GO
statements you need, you can still run this in a single transaction by surrounding it with:
BEGIN TRANSACTION;
BEGIN TRY
--Your migration code, with GO statements
END TRY
BEGIN CATCH
SELECT
ERROR_NUMBER() AS ErrorNumber
,ERROR_SEVERITY() AS ErrorSeverity
,ERROR_STATE() AS ErrorState
,ERROR_PROCEDURE() AS ErrorProcedure
,ERROR_LINE() AS ErrorLine
,ERROR_MESSAGE() AS ErrorMessage;
IF @@TRANCOUNT > 0
ROLLBACK TRANSACTION;
END CATCH;
IF @@TRANCOUNT > 0
COMMIT TRANSACTION;
GO
如果由于生成大型脚本而感到沮丧,则将 ALTER TABLE 行末尾的$ c> GO 对于SSMS中的replace来说是微不足道的,这类似于顶部的这个答案
If you are frustrated because you are generating large scripts, putting a GO
at the end of any ALTER TABLE
line is trivial with replace in SSMS, which would be something like the one at the top of this answer