Aracılığıyla paylaş


Yerel kod clr udf erişme

Bu örnek, bir işlev yerel (yönetilmeyen) c++ kodu derleme, veritabanınızdaki kullanıcı tanımlı bir işlev çağırmak gösterilmiştir.

Bu örnekte, çalışma dizini olmalıdır c:\test.

İlk c++ kodu derleyin:

// Win32Sleep.cpp
// compile with: /LD /link /noentry kernel32.lib
#include <windows.h>

extern "C"
__declspec( dllexport ) void _cdecl SleepyLoop(DWORD sleep_interval) {
   Sleep(sleep_interval);
}

// Win32Sleep.cpp
// compile with: /LD /link /noentry kernel32.lib
#include <windows.h>

extern "C"
__declspec( dllexport ) void _cdecl SleepyLoop(DWORD sleep_interval) {
   Sleep(sleep_interval);
}

Ardından, C# kodu derleme için derleyin:

// proc.cs
// compile with: /target:library
using System;
using System.Threading;
using System.Data.Sql;
using System.Runtime.InteropServices;

public class StoreProcedures {

   public static readonly uint SLEEP_LOOP_TIMES = 10;
   public static readonly uint SLEEP_DURATION = 1000;

   [DllImport(@"c:\test\Win32Sleep.dll")]
   internal static extern void SleepyLoop(uint sleepInterval);

   public static void SleepInProcedure(int loopTimes) {
      for ( int i = 0 ; i < loopTimes ; i++ ) {
         // invoke the unmanaged routine
         SleepyLoop(SLEEP_DURATION);
      }
   }
}

// proc.cs
// compile with: /target:library
using System;
using System.Threading;
using System.Data.Sql;
using System.Runtime.InteropServices;

public class StoreProcedures {

   public static readonly uint SLEEP_LOOP_TIMES = 10;
   public static readonly uint SLEEP_DURATION = 1000;

   [DllImport(@"c:\test\Win32Sleep.dll")]
   internal static extern void SleepyLoop(uint sleepInterval);

   public static void SleepInProcedure(int loopTimes) {
      for ( int i = 0 ; i < loopTimes ; i++ ) {
         // invoke the unmanaged routine
         SleepyLoop(SLEEP_DURATION);
      }
   }
}

Son olarak, aşağıdaki yürütme Transact-SQL:

USE MASTER
GO

IF DB_ID('testdb') IS NOT NULL
DROP DATABASE testdb
GO

CREATE DATABASE testdb
GO

USE testdb
GO

ALTER DATABASE testdb SET TRUSTWORTHY ON 
GO

sp_configure 'show advanced options', 1
GO
RECONFIGURE
GO
sp_configure 'clr enabled', 1
GO
RECONFIGURE
GO

CREATE ASSEMBLY myasm FROM 'c:\test\proc.dll' WITH PERMISSION_SET=UNSAFE 
go

CREATE PROCEDURE SleepProc(@loopTimes INT)
AS EXTERNAL NAME myasm.[StoreProcedures].[SleepInProcedure]
go

-- sleep 5 seconds
EXEC SleepProc 5
GO

USE MASTER
GO

IF DB_ID('testdb') IS NOT NULL
DROP DATABASE testdb
GO

CREATE DATABASE testdb
GO

USE testdb
GO

ALTER DATABASE testdb SET TRUSTWORTHY ON 
GO

sp_configure 'show advanced options', 1
GO
RECONFIGURE
GO
sp_configure 'clr enabled', 1
GO
RECONFIGURE
GO

CREATE ASSEMBLY myasm FROM 'c:\test\proc.dll' WITH PERMISSION_SET=UNSAFE 
go

CREATE PROCEDURE SleepProc(@loopTimes INT)
AS EXTERNAL NAME myasm.[StoreProcedures].[SleepInProcedure]
go

-- sleep 5 seconds
EXEC SleepProc 5
GO

Ayrıca bkz.

Kavramlar

Kullanım senaryoları ve ortak dil çalışma zamanı (clr) tümleştirme örnekleri