通过SqlClr制作Sql自动化批量执行脚本

简介: 原文:通过SqlClr制作Sql自动化批量执行脚本通过SqlClr制作Sql自动化批量执行脚本      在与同事一起做项目时,看到同事用sqlclr做批量执行脚本,感觉挺新奇的就上网搜集资料自己模仿跟做了个案例, 感觉挺不错的,现在想和大家分享一下,可能存在些错误的地方,大家就做个小参考吧.... 1.我们在做数据迁移或是数据库结构修改时,通常会写一些脚本文件之后逐个运行。
原文: 通过SqlClr制作Sql自动化批量执行脚本

通过SqlClr制作Sql自动化批量执行脚本

     在与同事一起做项目时,看到同事用sqlclr做批量执行脚本,感觉挺新奇的就上网搜集资料自己模仿跟做了个案例,

感觉挺不错的,现在想和大家分享一下,可能存在些错误的地方,大家就做个小参考吧....

1.我们在做数据迁移或是数据库结构修改时,通常会写一些脚本文件之后逐个运行。但是如果有数十或数百个脚本文件,

   那么就可以通过SqlClr制作Sql自动化执

2.比如现在ImportDataScript文件夹内有些脚本文件:

   

3.我们想让这9个脚本文件自动的依次执行,并且输出最终的执行情况并且生成一个日志写到ImportDataScript文件夹内的

   LogFile文件夹内的Logg.txt中。

4.我们预期结果:

   执行结果:(执行每个文件的开始时间、结束时间、执行总时间)

   

   输出日志:(名称、执行时间)

   

5.思路:首先我们通过sqlclr创建一个表值函数来获取脚本文件的本地路径的集合,然后遍历这个集合并通过sql exec xp_cmdshell命令

   来执行指定路径下的脚本文件,并通过sqlclr创建一个记录日志的的标量函数来逐条记录执行日志。

5.1创建sqlclr项目

5.1.1创建实体类:

 1 public class FilePathModel
 2     {
 3         public FilePathModel()
 4         {
 5 
 6         }
 7         public FilePathModel(string fileName, string filePath)
 8         {
 9             this.FileName = fileName;
10             this.FilePath = FilePath;
11         }
12         private string _FileName;
13 
14         public string FileName
15         {
16             get { return _FileName; }
17             set { _FileName = value; }
18         }
19         private string _FilePath;
20 
21         public string FilePath
22         {
23             get { return _FilePath; }
24             set { _FilePath = value; }
25         }
26     }

5.1.2创建表值函数:

 1 public partial class UserDefinedFunctions
 2 {
 3   [Microsoft.SqlServer.Server.SqlFunction
 4   (DataAccess = DataAccessKind.Read,
 5    TableDefinition = "FileName nvarchar(100),FilePath nvarchar(100)",
 6    FillRowMethodName = "FillTable", IsDeterministic = true)]
 7     public static IEnumerable GetScriptFilePath(SqlString fileRootPath)
 8     {
 9         
10         IList<FilePathModel> list = new List<FilePathModel>();
11         if (Directory.Exists(fileRootPath.Value))
12         {
13             DirectoryInfo di = new DirectoryInfo(fileRootPath.Value);
14             foreach (FileInfo fi in di.GetFiles())
15             {
16                 list.Add(new FilePathModel { FileName=fi.Name,FilePath=fi.FullName});
17             }
18         }
19         return list;
20     }
21   public static void FillTable(object obj, out SqlString fileName, out SqlString filePath)
22     {
23         fileName = "";
24         filePath = "";
25         FilePathModel fpModel = obj as FilePathModel;
26         if (fpModel != null)
27         {
28             fileName = fpModel.FileName;
29             filePath = fpModel.FilePath;
30         }
31     }
32 };

5.1.3创建写入日志的标量函数:

 1 public partial class UserDefinedFunctions
 2 {
 3     [Microsoft.SqlServer.Server.SqlFunction]
 4     public static SqlString ImportLog(SqlString pathStr, SqlString strName, SqlString Time)
 5     {
 6         // 在此处放置代码
 7 
 8         if (Directory.Exists(pathStr.Value))
 9         {
10             string filePathNew = Path.Combine(pathStr.Value, "Logg.txt");
11             FileInfo fi = new FileInfo(filePathNew);
12             if (!File.Exists(filePathNew))
13             {
14                 fi.Create();
15             }
16             using (StreamWriter sw = fi.AppendText())
17             {
18                 sw.WriteLine(strName.Value + "||" + Time.Value);
19             }
20             return new SqlString("完成");
21         }
22         else
23         {
24             return new SqlString("失败");
25         }
26     }
27 };

5.2写执行脚本:

--开启sqlclr
sp_configure 'show advanced options', 1; 
GO 
RECONFIGURE; 
GO 
sp_configure 'clr enabled', 1; 
GO 
RECONFIGURE; 
GO
--使用.net framework
ALTER database Test SET TRUSTWORTHY ON
ALTER assembly DataImprot
with permission_set = external_access
go
--
--开启【xp_cmdshell】权限
exec sp_configure 'xp_cmdshell', @configvalue = 1
reconfigure with override
go

--开启【opendatasource】权限
exec sp_configure @configname = 'Ad Hoc Distributed Queries', @configvalue = 1
reconfigure with override

--测试
DECLARE @fileRootPath nvarchar(100)
DECLARE @logFilePath nvarchar(100)
DECLARE @serverName nvarchar(100)
DECLARE @dataBaseName nvarchar(100)
DECLARE @loginName nvarchar(100)
DECLARE @passWord nvarchar(100)
--服务器名
SET @ServerName='PACTERA_GZF-PC'
--数据库名
SET @dataBaseName='Test'
--用户名
SET @loginName='sa'
--密码
SET @passWord='sa'
--脚本根路径
SET @fileRootPath='D:\ImportDataScript'
--日志文件路径.txt
SET @logFilePath='D:\ImportDataScript\LogFile'
DECLARE @FilePathTable table
(
    [FileName] nvarchar(100),
    FilePath nvarchar(100)
)
create table #CurFilePathTable
(
    Id int identity(1,1) primary key,
    [FileName] nvarchar(100),
    FilePath nvarchar(100),
    BeginTime datetime,
    EndTime datetime,
    ExcuteDate float
)
insert into @FilePathTable select [FileName], [FilePath] from dbo.GetScriptFilePath(@fileRootPath)
declare @FileName nvarchar(100)
declare @FilePath nvarchar(100)
declare @BeginTime datetime
declare @EndTime datetime
declare @sqlStr nvarchar(200)
declare cur_FilePath cursor for select [FileName], [FilePath] from @FilePathTable
open cur_FilePath
  fetch next from cur_FilePath into @FileName, @FilePath
while (@@fetch_status = 0)
begin
    set @BeginTime = getdate()
    set @sqlStr = 'exec xp_cmdshell ''osql -S '+@ServerName+' -U '+@loginName+' -P '+@passWord+' -i ' + @FilePath + ''''
    exec master..sp_executesql @sqlStr 
    set @EndTime = getdate()
    print @FileName
    insert into #CurFilePathTable ([FileName], FilePath, BeginTime,EndTime,ExcuteDate) values (@FileName, @FilePath, @BeginTime,@EndTime,datediff(second, @BeginTime, @EndTime))
    select dbo.ImportLog(@logFilePath,@FileName,convert(varchar(10),datediff(second, @BeginTime, @EndTime)))
    fetch next from cur_FilePath into @FileName, @FilePath
end
close cur_FilePath
deallocate cur_FilePath

select * FROM #CurFilePathTable
DROP TABLE #CurFilePathTable

5.3总结:

     感觉SqlClr就像是插件模型,通过嵌入.dll来实现更多的功能。

     利用SqlClr我们可以做许事情比如我们也可以在sqlserver端实现数据的加密解密等。

 

 

相关实践学习
日志服务之使用Nginx模式采集日志
本文介绍如何通过日志服务控制台创建Nginx模式的Logtail配置快速采集Nginx日志并进行多维度分析。
目录
相关文章
|
30天前
|
jenkins 持续交付
Jenkins自动化部署脚本
Jenkins自动化部署脚本
30 0
|
1月前
|
JavaScript 前端开发 测试技术
使用Selenium执行JavaScript脚本:探索Web自动化的新领域
本文介绍了如何在Selenium中使用JavaScript解决自动化测试中的复杂问题。Selenium的`execute_script`函数用于同步执行JS,例如滑动页面、操作时间控件等。在滑动操作示例中,通过JS将页面滚动到底部,点击下一页并获取页面信息。对于只读时间控件,利用JS去除readonly属性并设置新日期。使用JS扩展了Selenium的功能,提高了测试效率和精准度,适用于各种自动化测试场景。
46 1
|
2月前
|
Python
【速看】如何通过合理的封装,让你的自动化脚本更上一层楼!
【速看】如何通过合理的封装,让你的自动化脚本更上一层楼!
|
2月前
|
Shell 测试技术
Airtest如何自动连接重启后的设备并继续执行自动化脚本呢?
Airtest如何自动连接重启后的设备并继续执行自动化脚本呢?
|
2月前
|
SQL 测试技术 数据库
SQL注入,跨站脚本,跨站请求伪造,傻傻分不清楚
SQL注入,跨站脚本,跨站请求伪造,傻傻分不清楚
|
3月前
|
监控 安全 Shell
Shell脚本实现企业电脑屏幕监控的自动化部署与维护
企业信息安全一直是重要的议题,而屏幕监控是一种有效的手段之一。本文将介绍如何使用Shell脚本实现企业电脑屏幕监控的自动化部署与维护,并在结尾部分说明如何将监控到的数据自动提交到指定网站。
213 1
|
3月前
|
Shell Linux
shell 脚本常用于自动化执行文件备份与压缩的任务
shell 脚本常用于自动化执行文件备份与压缩的任务
29 1
|
3月前
|
Unix Shell Linux
在Unix/Linux操作系统中,Shell脚本广泛用于自动化任务
在Unix/Linux操作系统中,Shell脚本广泛用于自动化任务
26 2
|
4天前
|
Linux Shell Android开发
自动化脚本之GPIO/LED相关适用于Android/Linux
自动化脚本之GPIO/LED相关适用于Android/Linux
13 0
|
18天前
|
JSON 测试技术 持续交付
自动化测试与脚本编写:Python实践指南
【4月更文挑战第9天】本文探讨了Python在自动化测试中的应用,强调其作为热门选择的原因。Python拥有丰富的测试框架(如unittest、pytest、nose)以支持自动化测试,简化测试用例的编写与维护。示例展示了使用unittest进行单元测试的基本步骤。此外,Python还适用于集成测试、系统测试等,提供模拟外部系统行为的工具。在脚本编写实践中,Python的灵活语法和强大库(如os、shutil、sqlite3、json)助力执行复杂测试任务。同时,Python支持并发、分布式执行及与Jenkins、Travis CI等持续集成工具的集成,提升测试效率和质量。

热门文章

最新文章