Sql CLR创建一个简单的表值函数

1.创建面目:

 

2. 添加函数代码: 

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
using System;
using System.Data.Sql;
using Microsoft.SqlServer.Server;
using System.Collections;
using System.Data.SqlTypes;
using System.Diagnostics;
 
public class TabularEventLog
{
    [SqlFunction(TableDefinition =
@"logTime datetime
,Message nvarchar(4000)
,Category nvarchar(4000)
,InstanceId bigint",
        Name = "ReadEventLog", FillRowMethodName = "FillRow")]
    public static IEnumerable InitMethod(String logname)
    {
        return new EventLog(logname, Environment.MachineName).Entries;
    }
 
    public static void FillRow(Object obj, out SqlDateTime timeWritten,
        out SqlChars message, out SqlChars category,
        out long instanceId)
    {
        EventLogEntry eventLogEntry = (EventLogEntry)obj;
        timeWritten = new SqlDateTime(eventLogEntry.TimeWritten);
        message = new SqlChars(eventLogEntry.Message);
        category = new SqlChars(eventLogEntry.Category);
        instanceId = eventLogEntry.InstanceId;
    }
}

3. 脚本:

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
USE MASTER
GO
sp_configure 'show advanced options',1;
GO
RECONFIGURE;
GO
sp_configure 'clr enabled', 1;
GO
RECONFIGURE;
GO
--表值函数放在 db_study 库上
USE db_study
GO
--删除函数
IF OBJECT_ID('[dbo].[ReadEventLog]') IS NOT NULL
    DROP FUNCTION [dbo].ReadEventLog
GO
--删除程序集
IF EXISTS(SELECT * FROM SYS.ASSEMBLIES WHERE NAME='tvfEventLog')
    DROP  ASSEMBLY tvfEventLog
GO
--创建程序集, 设置为实际路径, 注意应设置为: UNSAFE
CREATE ASSEMBLY tvfEventLog  FROM'D:\Project\StudySimple\SqlServerProject1\bin\Debug\SqlServerProject1.dll' WITH PERMISSION_SET = UNSAFE
GO
--创建表值函数
CREATE FUNCTION dbo.ReadEventLog(@logname nvarchar(100))
RETURNS TABLE (
    logTime DATETIME
    ,Message nvarchar(4000)
    ,Category nvarchar(4000)
    ,InstanceId BIGINT
)
AS
    EXTERNAL NAME tvfEventLog.TabularEventLog.InitMethod
GO
--查询
SELECT TOP 10 T.logTime, T.Message, T.InstanceId
FROM dbo.ReadEventLog(N'Security') as T
ORDER BY logTime DESC

 

  

  

posted @   每天进步多一点  阅读(657)  评论(0编辑  收藏  举报
编辑推荐:
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
阅读排行:
· DeepSeek “源神”启动!「GitHub 热点速览」
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求
· 2 本地部署DeepSeek模型构建本地知识库+联网搜索详细步骤
历史上的今天:
2018-06-28 C# 可选参数 命名参数
点击右上角即可分享
微信分享提示