저장 프로시저 Return

이 섹션에서는 ADO.NET으로 저장 프로시저를 호출하는 예시를 다룹니다. ExecuteNonQuery로 영향받은 행 수를 얻는 동시에 저장 프로시저의 Return 반환값을 가져오는 방식을 확인합니다.

1. 데이터베이스 저장 프로시저 정의

create procedure mynewproc(@id int)
as
begin
    declare @cout int
    -- 갱신 구문
    update Article set title = '111' where id = @id
    -- 전달받은 매개변수보다 id가 큰 레코드 개수 집계
    select @cout = count(1) from Article where id > @id
    -- return으로 숫자 반환(SQL Server 저장 프로시저 return은 int 타입만 지원)
    return @cout
endCode language: PHP (php)

핵심: return @cout는 저장 프로시저의반환값이며 출력 매개변수 output과는 별개입니다.

2. C#에서 호출하기

string connectionString = "Data Source=.;Initial Catalog=db;Integrated Security=SSPI;";
using (SqlConnection connection = new SqlConnection(connectionString))
{
    connection.Open();
    SqlCommand command = new SqlCommand("mynewproc", connection);
    command.CommandType = CommandType.StoredProcedure;

    // 【중요】Return 반환값 매개변수 등록, 이름은 ReturnValue로 고정
    SqlParameter para = new SqlParameter(
        "ReturnValue",
        SqlDbType.Int,
        4,
        ParameterDirection.ReturnValue,
        false,0,0,string.Empty,DataRowVersion.Default,null);
    command.Parameters.Add(para);

    // 저장 프로시저 입력 매개변수 @id
    SqlParameter param = new SqlParameter("@id", SqlDbType.Int, 8);
    param.Value = 4;
    param.Direction = ParameterDirection.Input;
    command.Parameters.Add(param);

    // ExecuteNonQuery: 추가/수정/삭제 실행, 【update 구문의 영향받은 행 수】 반환
    int rowsAffected = command.ExecuteNonQuery();
    // 저장 프로시저 return이 넘겨준 값 읽기
    int result = (int)command.Parameters["ReturnValue"].Value;
}Code language: PHP (php)

권장 작성 방식

string connectionString = "Data Source=.;Initial Catalog=db;Integrated Security=SSPI;";
using (SqlConnection conn = new SqlConnection(connectionString))
using (SqlCommand cmd = new SqlCommand("mynewproc", conn))
{
    conn.Open();
    cmd.CommandType = CommandType.StoredProcedure;

    // 반환값 매개변수 등록(이름 고정: ReturnValue, Direction은 ReturnValue 필수)
    cmd.Parameters.Add("ReturnValue", SqlDbType.Int).Direction = ParameterDirection.ReturnValue;
    // 입력 매개변수
    cmd.Parameters.Add("@id", SqlDbType.Int).Value = 4;

    // rowsAffected = update 구문으로 수정된 레코드 수
    int rowsAffected = cmd.ExecuteNonQuery();
    // 저장 프로시저 return @cout 값 가져오기
    int procReturnVal = (int)cmd.Parameters["ReturnValue"].Value;
}Code language: JavaScript (javascript)

참고사항

1. int rowsAffected = command.ExecuteNonQuery();
  • 의미: DML 구문(update/delete/insert)으로 영향받은 행 개수
  • 이 예시: update Article set title='111' where id=@id가 일치하여 수정한 레코드 수
  • 저장 프로시저 return 반환값이 아닙니다. 둘은 완전히 독립적입니다
2. ReturnValue 반환값 매개변수
  1. 매개변수 이름은고정 문자열 ReturnValue를 강제 사용하며 임의로 바꿀 수 없음
  2. Direction = ParameterDirection.ReturnValue
  3. SQL Server 저장 프로시저의 return 숫자는 int 타입만 전달 가능
  4. ExecuteNonQuery() 실행 후에야 이 매개변수의 값을 조회할 수 있음

  • return 반환값: 한 개만 사용 가능, int 타입만 지원
  • output 출력 매개변수: 여러 개 선언 가능, 다양한 데이터 타입 지원

차이점

-- 저장 프로시저 내부
update Article set title='111' where id=4; -- 1건 수정된다고 가정
return 10; -- return 반환값Code language: PHP (php)

실행 후:

  • rowsAffected = 1 (update로 영향받은 행 수)
  • procReturnVal = 10 (return으로 전달된 값)

정리

메서드반환 내용사용 시나리오
ExecuteReaderSqlDataReader(스트리밍 다중 행)여러 건 데이터 조회
SqlDataAdapter.FillDataSet/DataTable(오프라인 테이블)WinForm 컨트롤 테이블 바인딩
ExecuteScalarobject(첫 행 첫 열)단일 집계 결과만 필요할 때
ExecuteNonQueryint(영향받은 행 수)+ReturnValue 반환값추가/수정/삭제, 저장 프로시저 상태 코드가 필요할 때

저장 프로시저 Return

Previous:

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다