Share via


방법: CLR SQL Server 저장 프로시저 만들기 및 실행

업데이트: 2007년 11월

저장 프로시저 항목을 SQL Server 프로젝트에 추가하여 SQL 저장 프로시저를 만듭니다. SQL Server를 실행하는 컴퓨터에 배포한 후에는 관리 코드로 만든 저장 프로시저를 다른 저장 프로시저처럼 호출하고 실행할 수 있습니다.

참고:

기본적으로 CLR(공용 언어 런타임) 통합 기능은 Microsoft SQL Server에서 해제되어 있으며 SQL Server 프로젝트 항목을 사용하려면 이 기능을 사용하도록 설정해야 합니다. CLR 통합 기능을 사용하도록 설정하려면 sp_configure 저장 프로시저의 clr enabled 옵션을 사용합니다. 자세한 내용은 CLR 통합 설정을 참조하십시오.

참고:

실제 설정이나 버전에 따라서 화면에 나타나는 대화 상자와 메뉴 명령이 도움말의 설명과 다를 수 있습니다. 설정을 변경하려면 도구 메뉴에서 설정 가져오기 및 내보내기를 선택합니다. 자세한 내용은 Visual Studio 설정을 참조하십시오.

SQL Server 저장 프로시저 만들기

SQL Server 저장 프로시저를 만들려면

  1. 기존의 SQL Server 프로젝트를 열거나 새 프로젝트를 만듭니다. 자세한 내용은 방법: SQL Server 프로젝트 만들기를 참조하십시오.

  2. 프로젝트 메뉴에서 새 항목 추가를 선택합니다.

  3. 새 항목 추가 대화 상자에서 저장 프로시저를 선택합니다.

  4. 새 저장 프로시저의 이름을 입력합니다.

  5. 저장 프로시저가 실행될 때 실행할 코드를 추가합니다. 다음 예제를 참조하십시오.

    참고:

    C++ 예제는 /clr:safe 컴파일러 옵션을 사용하여 컴파일해야 합니다.

  6. Visual Basic 및 Visual C#의 경우 솔루션 탐색기에서 TestScripts 폴더를 열고 Test.sql 파일을 두 번 클릭합니다.

    Visual C++의 경우 솔루션 탐색기에서 debug.sql 파일을 엽니다.

  7. Test.sql(Visual C++의 경우 debug.sql) 파일에 저장 프로시저를 실행하는 코드를 추가합니다. 아래의 두 번째 예제를 참조하십시오.

  8. F5 키를 눌러 저장 프로시저를 빌드, 배포 및 디버깅합니다. 디버깅하지 않고 배포하는 방법에 대한 자세한 내용은 방법: SQL Server에 SQL Server 프로젝트 항목 배포를 참조하십시오.

  9. 출력 창에서 결과를 확인하고 다음에서 출력 보기: 데이터베이스 출력을 선택합니다.

예제

다음 코드 예제에서는 Adventure Works 샘플 데이터베이스의 Currency 테이블에 레코드를 삽입하는 저장 프로시저를 만듭니다. 저장 프로시저를 만든 후에는 SQL Server에 배포합니다. 자세한 내용은 방법: SQL Server에 SQL Server 프로젝트 항목 배포를 참조하십시오.

Imports System
Imports System.Data
Imports System.Data.SqlClient
Imports System.Data.SqlTypes
Imports Microsoft.SqlServer.Server

Partial Public Class StoredProcedures

    <SqlProcedure()> _
    Public Shared Sub InsertCurrency( _
        ByVal currencyCode As SqlString, ByVal name As SqlString)

        Using conn As New SqlConnection("context connection=true")

            Dim InsertCurrencyCommand As New SqlCommand()
            Dim currencyCodeParam As New SqlParameter("@CurrencyCode", SqlDbType.NVarChar)
            Dim nameParam As New SqlParameter("@Name", SqlDbType.NVarChar)

            currencyCodeParam.Value = currencyCode
            nameParam.Value = name


            InsertCurrencyCommand.Parameters.Add(currencyCodeParam)
            InsertCurrencyCommand.Parameters.Add(nameParam)

            InsertCurrencyCommand.CommandText = _
                "INSERT Sales.Currency (CurrencyCode, Name, ModifiedDate)" & _
                " VALUES(@CurrencyCode, @Name, GetDate())"

            InsertCurrencyCommand.Connection = conn

            conn.Open()
            InsertCurrencyCommand.ExecuteNonQuery()
            conn.Close()
        End Using
    End Sub
End Class
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);

            currencyCodeParam.Value = currencyCode;
            nameParam.Value = name;

            InsertCurrencyCommand.Parameters.Add(currencyCodeParam);
            InsertCurrencyCommand.Parameters.Add(nameParam);

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

            InsertCurrencyCommand.Connection = conn;

            conn.Open();
            InsertCurrencyCommand.ExecuteNonQuery();
            conn.Close();
        }
    }
}
#include "stdafx.h"

#using <System.dll>
#using <System.Data.dll>
#using <System.Xml.dll>

using namespace System;
using namespace System::Data;
using namespace System::Data::Sql;
using namespace System::Data::SqlClient;
using namespace System::Data::SqlTypes;
using namespace Microsoft::SqlServer::Server;

// In order to debug your Stored Procedure, add the following to your debug.sql file:
//
// EXEC InsertCurrency_CPP 'AAA', 'Currency Test'
// SELECT * FROM Sales.Currency WHERE CurrencyCode = 'AAA'

public ref class StoredProcedures
{
public:
    [SqlProcedure]
    static void InsertCurrency_CPP(SqlString currencyCode, SqlString name)
    {
        SqlConnection ^conn = gcnew SqlConnection("context connection=true");

        SqlCommand ^insertCurrencyCommand = gcnew SqlCommand();
        SqlParameter ^currencyCodeParam =
            gcnew SqlParameter("@CurrencyCode", SqlDbType::NVarChar);
        SqlParameter ^nameParam =
            gcnew SqlParameter("@Name", SqlDbType::NVarChar);

        insertCurrencyCommand->CommandText =
            "insert Sales.Currency(CurrencyCode, Name, ModifiedDate)" +
            " values(@CurrencyCode, @Name)";
        insertCurrencyCommand->Connection = conn;

        conn->Open();
        insertCurrencyCommand->ExecuteNonQuery();

        conn->Close();
    }
};

프로젝트의 TestScripts 폴더에 있는 Test.sql(Visual C++의 경우 debug.sql) 파일에 저장 프로시저를 실행 및 테스트하는 코드를 추가합니다. 예를 들어, 저장 프로시저를 배포한 경우 EXEC <StoredProcedureName>을 호출하고 필요한 매개 변수를 전달하여 저장 프로시저를 실행합니다. 저장 프로시저가 값을 반환하지 않으면 저장 프로시저가 데이터에 적용되었는지 확인하는 코드를 추가로 삽입합니다.

EXEC InsertCurrency 'AAA', 'Currency Test'
SELECT * from Sales.Currency where CurrencyCode = 'AAA'

참고 항목

작업

방법: SQL Server 프로젝트 만들기

방법: CLR SQL Server 저장 프로시저 만들기 및 실행

방법: CLR SQL Server 트리거 만들기 및 실행

방법: CLR SQL Server 집계 만들기 및 실행

방법: CLR SQL Server 사용자 정의 함수 만들기 및 실행

방법: CLR SQL Server 사용자 정의 형식 만들기 및 실행

연습: 관리 코드로 저장 프로시저 만들기

방법: SQL CLR 저장 프로시저 디버깅

개념

SQL Server CLR 통합 소개

관리 코드를 사용하여 데이터베이스 개체를 만드는 경우의 이점

SQL Server 프로젝트에 대한 항목 템플릿

참조

SQL Server 프로젝트 및 데이터베이스 개체의 특성

기타 리소스

SQL CLR 데이터베이스 디버깅