-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathap_BatchExec8.sql
118 lines (97 loc) · 2.8 KB
/
ap_BatchExec8.sql
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
create proc util.ap_BatchExec8
-- Execute specified sql files.
@ServerName sysname = '.\rc',
@UserId sysname = 'sa',
@PWD sysname = 'my,password',
@DirName varchar(400)='C:\sql\test',
@File varchar(400) = 'list.txt',
@UseTransaction int = 0,
@debug int = 0
as
set nocount on
declare @FilePath varchar(500),
@FileId int,
@MaxFileID int,
@OldFileId int,
@Cmd varchar(1000),
@i int,
@iOld int,
@max int,
@s varchar(max),
@line varchar(max)
--- Get list of files
create table #FileList (FileId int identity(1,1),
FileName varchar(500))
select @Cmd = 'cd ' + @DirName + ' & type ' + @File
insert #FileList (FileName)
exec master.sys.xp_cmdshell @Cmd
-- remove empty rows and comments
delete #FileList where FileName is null
delete #FileList where FileName like '--%'
if @debug <> 0
select * from #FileList
create table #script (SQL varchar(max),
LineId int identity)
select @FileId = Min (FileId),
@MaxFileID = Max(FileId)
from #FileList
-- loop throguh files
WHILE @FileId <= @MaxFileID
BEGIN
-- get name of the file to be processed
select @FilePath = @DirName + '\' + FileName
from #FileList
where FileId = @FileId
if @FilePath <> ''
BEGIN
if @debug <> 0
print 'Reading ' + @FilePath
set @cmd = 'Type "' + @FilePath + '"'
insert #script (SQL)
exec master.sys.xp_cmdshell @Cmd
Select @i = Min (LineId),
@max = Max(LineId),
@s = ''
from #script
while @i <= @max
begin
Select @line = Coalesce(SQL, ' ')
from #script
where LineId = @i
if @debug <> 0
select 'read line =', @i i, @line line
if Left(@line, 2) <> 'GO'
begin
-- the the line and go another round
select @s = @s + char(13) + char(10) + @line
if @debug <> 0
select @s [@s]
end
else
begin
begin try
if @debug = 0
exec sp_sqlexec @s
else
select @s
end try
begin catch
print Error_message()
print 'Process stopped.'
return
end catch
set @s = ''
end
-- contunue line by line
set @iOld = @i
select @i = Min(LineId)
from #script
where LineId > @iOld
end
END
-- get next file
set @FileID = @FileId + 1
select @fileID FileId
truncate table #script
END
return