9 out of 42 rated this helpful - Rate this topic

Walkthrough: Creating a Stored Procedure in Managed Code 

Stored procedures for SQL Server 2005 databases can now be written in managed code using .NET Framework languages such as Visual Basic, C#, and C++. Stored procedures written in managed code are called CLR stored procedures.

You can create SQL stored procedures by adding Stored Procedure items to SQL Server projects. After successfully deploying to a SQL Server, stored procedures created in managed code are called and executed like any other stored procedures.

Tasks illustrated in this walkthrough include:

  • Creating a new Windows Application project.

  • Creating a stored procedure in managed code.

  • Deploying the stored procedure to a SQL Server 2005 database.

  • Creating a script to test the stored procedure on the database.

  • Querying data in the database to confirm that the stored procedure executes properly.

In order to complete this walkthrough, you need:

To create the new SQL Server project

  1. From the File menu, create a new project.

  2. Select SQL Server Project, name the project SQLCLRStoredProcedure and click OK. For more information, see How to: Create a SQL Server Project.

This walkthrough requires a connection to the AdventureWorks sample database running on SQL Server 2005. If a connection to the AdventureWorks sample database is available in Server Explorer, then it will be listed in the Add Database Reference Dialog Box.

NoteNote

The common language runtime (CLR) integration feature is off by default in Microsoft SQL Server and must be enabled in order to use SQL Server project items. To enable CLR integration, use the clr enabled option of the sp_configure stored procedure. From more information, see Enabling CLR Integration.

To connect to the AdventureWorks sample database

After creating the SQL Server project, add a stored procedure to it.

To create the SQL Server stored procedure

  1. From the Project menu, choose Add New Item.

  2. Select Stored Procedure in the Add New Item Dialog Box.

  3. Type InsertCurrency as the Name for the new stored procedure.

  4. Click Add.

  5. Replace the code in the Code Editor with the following:

    NoteNote

    C++ examples must be compiled with the /clr:safe compiler option.

    using System;
    using System.Data;
    using System.Data.SqlClient;
    using System.Data.SqlTypes;
    using Microsoft.SqlServer.Server;
    
    
    public partial class StoredProcedures
    {
        [SqlProcedure()]
        public static void InsertCurrency_CS(
            SqlString currencyCode, SqlString name)
        {
            using (SqlConnection conn = new SqlConnection("context connection=true"))
            {
                SqlCommand InsertCurrencyCommand = new SqlCommand();
                SqlParameter currencyCodeParam = new SqlParameter("@CurrencyCode", SqlDbType.NVarChar);
                SqlParameter nameParam = new SqlParameter("@Name", SqlDbType.NVarChar);
    
    
    
                InsertCurrencyCommand.CommandText =
                    "INSERT Sales.Currency (CurrencyCode, Name, ModifiedDate)" +
                    " VALUES(@CurrencyCode, @Name)";
    
                InsertCurrencyCommand.Connection = conn;
    
                conn.Open();
                InsertCurrencyCommand.ExecuteNonQuery();
                conn.Close();
            }
        }
    }
    
    

After you create a new stored procedure, it can be built, deployed to the SQL server, and debugged by pressing F5. First, in the Test.sql file found in the TestScripts folder of your project, add code to execute and test your stored procedure. For Visual C++, this file is named debug.sql. For more information on creating test scripts see, How to: Edit the Test.sql Script to Run SQL Objects.

For more information on debugging SQL, see Debugging SQL Database Objects.

To deploy, and run the InsertCurrency stored procedure

  1. For Visual Basic and Visual C#, in Solution Explorer, expand the TestScripts folder and double-click the Test.sql file.

    For Visual C++, in Solution Explorer, double-click the debug.sql file.

  2. Replace the code in the Test.sql (debug.sql in Visual C++) file with the following code:

    EXEC InsertCurrency 'AAA', 'Currency Test'
    SELECT * from Sales.Currency where CurrencyCode = 'AAA'
    
  3. Press F5 to build, deploy, and debug the stored procedure. For information on deploying without debugging, see How to: Deploy SQL Server Project Items to a SQL Server.

    View the results in the Output window and select Show output from: Database Output.

Did you find this helpful?
(1500 characters remaining)
Community Content Add
Annotations FAQ
Re: Parameter Sizes

It is not ignoring it, it will ether throw an error or clip the string length to 20 on that line (I dont remember offhand); it sounds as if you are wanting though is to change the external interface, which is determined by the function declaration parameters, in the example it only indicates it will be a SqlString, to limit the size to 20 you would modify the function declaration like this:

public static void InsertCurrency_CPP( [SqlFacet(MaxSize=20)] SqlStringcurrencyCode, [SqlFacet(MaxSize=20)] SqlString name){
deliberate mistake to hone debug skills?

Maybe I missed the point of the sample code, and it is intentionally wrong in order to demonstrate the super debugging environment. If not, the following code is more likely to work:

using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
  
public partial class StoredProcedures {
[SqlProcedure]
public static void InsertCurrency(SqlString currencyCode, SqlString name) {
using(SqlConnection cn = new SqlConnection("context connection=true")) {
SqlCommand cmd = new SqlCommand();
cmd.Parameters.Add("@CurrencyCode", SqlDbType.NVarChar).Value = currencyCode;
cmd.Parameters.Add("@Name", SqlDbType.NVarChar).Value = name;
cmd.CommandText = "INSERT Sales.Currency (CurrencyCode, Name) VALUES(@CurrencyCode, @Name)";
cmd.Connection = cn;
cn.Open();
cmd.ExecuteNonQuery();
   cn.Close();
}
}
};

hey ho.

parameter sizes
It seems to ignore any size you assign to a parameter - or am I doing something wrong?

Whether I set ... new SqlParameter("@CurrencyCode", SqlDbType.NVarChar, 20); .... or leave the 20 out, it creates a 4000 sized parameter.
Extra settings for the walkthrough
The default configuration of sql-server does not have the "clr enabled" option as true. Without it being true, your result-set will always be empty. First order of business is to enable it. Simplest way to do it would beto run the following script.

EXEC sp_configure 'show advanced options' , '1';

go
reconfigure;
go
EXEC sp_configure 'clr enabled' , '1'
go
reconfigure;
-- Turn advanced options back off
EXEC sp_configure 'show advanced options' , '0';
go

Having done that, you should be able to get the resultsets in the output window.
If even that does not work, you want to use SqlPipe.so, the code in the sample above translates to :

SqlPipe pipe = SqlContext.Pipe;

using (SqlConnection conn = new SqlConnection("context connection=true"))
{
SqlCommand InsertCurrencyCommand = new SqlCommand();
SqlParameter currencyCodeParam = new SqlParameter("@CurrencyCode", SqlDbType.NVarChar);
SqlParameter nameParam = new SqlParameter("@Name", SqlDbType.NVarChar);


InsertCurrencyCommand.CommandText =
"INSERT Sales.Currency (CurrencyCode, Name, ModifiedDate)" +
" VALUES(@CurrencyCode, @Name)";

InsertCurrencyCommand.Connection = conn;

conn.Open();
// InsertCurrencyCommand.ExecuteNonQuery();
pipe.ExecuteAndSend(cmd);
conn.Close();
}