Академический Документы
Профессиональный Документы
Культура Документы
logging in SQL Server Use ADO.NET in the usual way Has to be enabled before use Use SQLCLR project Add/New Item Write your code Build/Deploy solution Try it! Create your class Add static method - will become your SP Compile your code, produce DLL assembly create assembly <name> from '<path to your dll>' with <options> Register the assembly in SQL Server create procedure <name> as external name <assembly>.<your class>.<your method> Register the stored procedure Try it! e.g. string parsing, scientific math, etc. Computation-oriented algorithms Stored procedures Functions User defined types User defined aggregates Trigger
[Microsoft.SqlServer.Server.SqlProcedure()] public static void SampleSP( int rating ) { SqlConnection conn = new SqlConnection("context connection=true"); conn.Open(); SqlCommand cmd = new SqlCommand( "SELECT ... WHERE CR<=@rating", conn); cmd.Parameters.AddWithValue( "@rating", rating ); SqlContext.Pipe.ExecuteAndSend( cmd ); }
Different DB session Separate connection! Different SET options Be careful about transactions! Your don't see your temp tables etc. No asynchronous command execution SqlDependency is not supported SqlConnection c = new SqlConnection("context connection=true"); c.Open(); Microsoft.SqlServer.Server.SqlContext surfaces the context. Read or write to the local SQL Server where the stored proc, function, type or aggregate is running. "Context Connection" Connection String // statement similar to T-SQL's PRINT SqlContext.Pipe.Send( "Hello World!" ); // return resultset from stored proc SqlCommand cmd = new SqlCommand( "SELECT..." ); SqlContext.Pipe.ExecuteAndSend( cmd ); // build and return resultset SqlDataRecord rec = new SqlDataRecord(...); SqlContext.Pipe.SendResultsStart( rec ); rec.SetString(...); ... SqlContext.Pipe.SendResultsRow( rec ); ... SqlContext.Pipe.SendResultsEnd();
Visual Studio
Restrictions
How
Data Access
SDK
SqlPipe class represents the connection to the client MARS Some ADO.NET features not supported SqlBulkCopy SqlNotificationRequest SqlCommand.Cancel Credentials, impersonation Common transaction handling
create assembly SQLCLRDemo from '...' with permission_set = unsafe Permission set controls level of access of CLR procedures
Don't just wrap SQL Still use INSERT, UPDATE, DELETE and SELECT instead of cursors! Still use set-oriented operations, avoid cursors Use context connection if possible
No access to external resources safe allows access to resources such as files, networks, environmental variables, and the registry external access unrestricted access to resources, can call unmanaged code unsafe