一、环境
1、在服务器端安装sql server服务器(https://yunpan.cn/cgzyDqR3VTNm5 访问密码 3f69)
2、在客服端安装ftp服务器软件(https://yunpan.cn/cYcxnt6Bz2QkV 访问密码 5931)
二、服务器端创建表及存储过程
1、 创建表:
USE [WFS] GO /****** Object: Table [dbo].[ExecBatLog] Script Date: 03/07/2016 15:20:22 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[ExecBatLog]( [ID] [int] NOT NULL, [BatCmd] [nvarchar](max) NULL, [StartTime] [nvarchar](30) NULL, [EndTime] [nvarchar](30) NULL, [ErrMark] [nvarchar](1024) NULL, CONSTRAINT [PK_ID] 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
2、创建存储过程:
USE [WFS] GO /****** Object: StoredProcedure [dbo].[sp_ExecBat] Script Date: 03/07/2016 15:19:58 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: <moki> -- Create date: <20160122> -- Description: <执行SQL语句> -- ============================================= CREATE PROCEDURE [dbo].[sp_ExecBat] -- Add the parameters for the stored procedure here @SqlBat NVARCHAR(4000) AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. SET NOCOUNT ON; DECLARE @ID INT DECLARE @RET INT SET @RET = 1 SELECT @ID=COUNT(*)+1 FROM ExecBatLog INSERT INTO [dbo].[ExecBatLog] ([ID],[BatCmd],[StartTime],[EndTime],[ErrMark]) SELECT @ID,@SqlBat,CONVERT(VARCHAR(20),GETDATE(),120),NULL,NULL BEGIN TRY EXEC master.dbo.xp_cmdshell @SqlBat,NO_OUTPUT UPDATE [dbo].[ExecBatLog] SET [EndTime]=CONVERT(VARCHAR(20),GETDATE(),120),[ErrMark]='执行完成:成功' WHERE ID=@ID END TRY BEGIN CATCH UPDATE [dbo].[ExecBatLog] SET [EndTime]=CONVERT(VARCHAR(20),GETDATE(),120),[ErrMark]='执行失败:'+ERROR_MESSAGE() WHERE ID=@ID SET @RET = -1 END CATCH RETURN @RET END GO
三、客服端写个软件去调用服务器端sp_ExecBat存储过程,并执行bat语句即可实现
对服务器端磁盘文件的下载或上传。批处理语句举例如下:
DECLARE @BAT VARCHAR(4000) SET @BAT = 'MD E:\FtpTmpData\'+ '&echo OPEN 172.18.134.299>E:\FtpTmpData\test.ftp'+ '&echo user dataimport >>E:\FtpTmpData\test.ftp'+ '&echo password01! >>E:\FtpTmpData\test.ftp'+ '&echo asc >>E:\FtpTmpData\test.ftp'+ '&echo prompt off >>E:\FtpTmpData\test.ftp'+ '&echo lcd >>E:\FtpTmpData\test.ftp'+ '&echo cd 20151217 >>E:\FtpTmpData\test.ftp'+ '&echo mget BL75040D.BTD.gz.201512170>>E:\FtpTmpData\test.ftp'+ '&echo mput HELLO.txt>>E:\FtpTmpData\test.ftp'+ '&echo bye >>E:\FtpTmpData\test.ftp'+ '&echo exit >>E:\FtpTmpData\test.ftp'+ '&E: &CD E:\FtpTmpData\ &ftp.exe -n -s:test.ftp' EXEC WFS.dbo.sp_ExecBat @BAT --SELECT * FROM WFS.dbo.ExecBatLog --truncate table WFS.dbo.ExecBatLog