output 사용하기
아래와 같이 test라는 이름의 procedure를 작성하고 @temp1, @temp2를 output으로 설정해보자.
create proc test
(
@temp1 int output,
@temp2 varchar(20) output
)
as
begin
set @temp1 = 1
set @temp2 = 'outValue'
end
Form1에서 아래와 같이 코드를 작성한후 실행해 본다.
public Form1()
{
InitializeComponent();
test();
}
private void test()
{
string connStr = @"Data Source=SqlServer이름;Initial Catalog=DataBase이름;Integrated Security=True";
SqlConnection cn = new SqlConnection();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "test";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = cn;
SqlParameter param;
param = new SqlParameter();
param.ParameterName = "@temp1";
param.SqlDbType = SqlDbType.Int;
param.Value = 0;
param.Direction = ParameterDirection.Output;
cmd.Parameters.Add(param);
param = new SqlParameter();
param.ParameterName = "@temp2";
param.SqlDbType = SqlDbType.VarChar;
param.Size = 20;
param.Value = "inValue";
param.Direction = ParameterDirection.Output;
cmd.Parameters.Add(param);
cn.ConnectionString = connStr;
cn.Open();
cmd.ExecuteNonQuery();
MessageBox.Show(cmd.Parameters["@temp1"].Value.ToString());
MessageBox.Show(cmd.Parameters["@temp2"].Value.ToString());
cn.Close();
}
실행해보면 분명히 temp1에는 0을 셋팅했지만 1이 출력될것이다.
temp2역시 inValue를 셋팅하였지만 outValue 라고 출력될 것이다.
ExecuteNonQuery() 는 반환하는 데이터가 없다고 했지만 위와 같이 output을 설정하면 DB에서 값을 넣어주면 넣어준 값을 그대로 받아다가 사용할 수 있다.