我正在尝试连接SQL Server并在安装设置时执行脚本文件。我设法执行一个没有GO
语句的简单脚本。
问题:有没有办法传递(跳过)GO
字并执行脚本?
ADOConnection.ConnectionString :=
'Provider=SQLOLEDB;' +
'Data Source=' + ServerEdit.Text + ';' +
'User Id=' + UsernameEdit.Text + ';' +
'Password=' + PasswordEdit.Text + ';' +
'Trusted_Connection=no;';
end;
ADOConnection.Open;
try
ADOCommand := CreateOleObject('ADODB.Command');
ADOCommand.ActiveConnection := ADOConnection;
ScriptPath := ExpandConstant('{tmp}\Script2.sql');
if LoadStringFromFile(ScriptPath, ssquery) then
begin
StringChangeEx(ssquery, 'GO', '', True);
SQLQuery := ssquery
ADOCommand.CommandText := SQLQuery;
ADOCommand.Execute(NULL, NULL, adCmdText or adExecuteNoRecords);
Result := True;
end;
finally
ADOConnection.Close;
end;
Script2.sql
USE northwind3
GO
/****** Object: StoredProcedure [dbo].[Customers By City] Script Date: 5/25/2016 8:35:45 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[Customers By City]
-- Add the parameters for the stored procedure here
(@param1 NVARCHAR(20))
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
SELECT CustomerID, ContactName, CompanyName, City from Customers as c where c.City=@param1
END
GO
/****** Object: StoredProcedure [dbo].[Customers Count By Region] Script Date: 5/25/2016 8:35:45 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[Customers Count By Region]
-- Add the parameters for the stored procedure here
(@param1 NVARCHAR(15))
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
DECLARE @count int
SELECT @count = COUNT(*)FROM Customers WHERE Customers.Region = @Param1
RETURN @count
END
注意:我以类似的方式使用ADOB进行连接TLama's回答How to connect to MS SQL Server using InnoSetup?除了我的情况,我必须在我的脚本中包含GO
。
谢谢。
答案 0 :(得分:0)
您可以将SQL脚本拆分为单独的脚本文件,而不是go
语句,并按顺序单独执行。
如果这不是一个选项,则必须使用支持go
语句的API /工具,即sqlcmd
工具,而不是ADO。
或者只是在通过ADO执行脚本之前加载脚本文件并删除go
语句。
您可以使用StringChange
function。