当我使用SMO对IncludeIfNotExists设置为true的过程进行脚本编写时,它将首先创建该过程,然后对其进行更改。有没有办法以动态SQL样式创建过程? (就像在SSMS中一样)
这是我从SMO得到的:
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_a]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[proc_a] AS'
END
GO
ALTER PROCEDURE [dbo].[proc_a]
AS
BEGIN
-- etc..
END
GO
我想要这样的东西:
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_a]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[proc_a]
AS
BEGIN
-- etc..
END
'
END
GO
答案 0 :(得分:0)
对于感兴趣的任何人,使用SQL 2008 SMO程序集生成具有Dynamic-SQL样式的代码,而使用SQL 2017生成具有ALTER语句的代码。
[System.Reflection.Assembly]::Load("Microsoft.SqlServer.Smo, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91")
[System.Reflection.Assembly]::Load("Microsoft.SqlServer.SmoExtended, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91")
[System.Reflection.Assembly]::Load("Microsoft.SqlServer.Smo, Version=14.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91")
[System.Reflection.Assembly]::Load("Microsoft.SqlServer.SmoExtended, Version=14.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91")