-2

私のプロジェクトの1つでは、C#を使用してTextBoxで次の手順で返された値を読み取る必要があります。

c#を使用して次の手順で返されたTextBoxで@aを読み取るコードを誰でも書くことができますか??

create procedure [dbo].[Test]    
as    
declare    
@a numeric(5)    
begin    
set @a = (select COUNT(*) from Emp);    
return @a   
end 

私はこれを試しました

SqlConnection cn = new SqlConnection("data source=localhost;initial catalog=acc;uid=sa;pwd=fantastic");
cn.Open();
SqlCommand cmd = cn.CreateCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "Test";
Int32 i = Convert.ToInt32(cmd.ExecuteScalar());
textBox1.Text = i.ToString();
4

2 に答える 2

2

-- 部分的にコピーして貼り付けたもので、ほとんどが頭から離れていますが、試してみてください。

SqlConnection con = new SqlConnection(connectionstring);
SqlCommand com = new SqlCommand("test", con);
com.CommandType = CommandType.StoredProcedure;
SqlParamter returnVal = new SqlParameter("RETURN_VALUE", SqlDbType.Int);
returnVal.Direction = ParameterDirection.ReturnValue;
com.Parameters.Add(returnVal);
com.Connection.Open();
com.ExecuteNonQuery();
int A = returnVal.value;
con.Close();

ExecuteScalar: "クエリを実行し、クエリによって返された結果セットの最初の行の最初の列を返します。" フィールドではなく、戻り値を返しています。スカラーを使用する場合は、ストアド プロシージャを編集して、実際に次のようにフィールドを返す必要があります。

create procedure [dbo].[Test] 
as 
begin 

select (select COUNT(*) from Emp)

end  
于 2012-04-20T10:10:00.153 に答える
1

returnパラメータを使用するか(riffnlの回答を参照)、spの「return」を「select」に変更することができます。

ExecuteScalarは戻り値をキャッチせず、最初のselected値のみをキャッチします。

于 2012-04-20T10:22:12.733 に答える