2014-02-07 2 views
0

에 약간의 문제가 있습니다. 내 값은 항상 null입니다. 나는 이유를 모른다. 아래저장 프로 시저 SQL Server 2008 출력 매개 변수 C#

코드 : # C 지금

SET ANSI_NULLS ON 
GO 
SET QUOTED_IDENTIFIER ON 
GO 
ALTER PROCEDURE [dbo].[UsunTowar] 
    @id int output 
AS SET NOCOUNT ON 
BEGIN 
    if Exists (select top 1 Towar from Zamowienia where Towar = @id) 
     begin 
      set @id = 0 
     end 
    else 
     begin 
      delete from Towary where ID = @id 
      set @id = 1 
     end 
END 

:

con.Open(); 
SqlCommand cmd = con.CreateCommand(); 

cmd.CommandText = "EXECUTE UsunTowar @id"; 

cmd.Parameters.Add("@id", SqlDbType.Int).Value = id; 
cmd.Parameters["@id"].Direction = ParameterDirection.Output; 

cmd.ExecuteNonQuery(); 

string result = cmd.Parameters["@id"].Value.ToString(); 

con.Close(); 

값 문자열 'result' 항상 null입니다. 나는 여러 가지 방법을 시도했다. 반환 값은 0 또는 1이어야합니다.

코드 SQL이 좋습니다. 도와주세요.

+2

저장 프로 시저가 아무것도 반환하지 않습니다. 'select @ id' 나'return @ id'를 SP의 마지막 라인으로 사용할 수 있습니다. 단일 값을 반환하는 경우에도 ExecuteScalar를 사용할 수 있습니다. – Miller

+0

한 가지 더 있습니다. 행이 없을 때 삭제하려고합니다. 그러므로 존재하기 전에'NOT'을 추가하십시오. – Miller

+0

'select @ id'와'return @ id'를 시도했지만 여전히 'result'값은 null입니다. 이것은 매우 중요하며 어떤 아이디어도 없습니다. –

답변

1

나는 이것을 사용 :

using(SqlConnection conn = new SqlConnection("myConnectionString")) 
    { 
     using(SqlCommand cmd = new SqlCommand("myStoredProcedure", conn)) 
     { 
      cmd.CommandType = CommandType.StoredProcedure; 
      cmd.Parameters.Add("@id", SqlDbType.Int).Direction = ParameterDirection.Output; 
      try 
      { 
       conn.Open(); 
       cmd.ExecuteNonQuery(); 
       // -1 if null 
       int id = 0; 
       if (!int.TryParse(cmd.Parameters["@id"].value, out id)) 
        id = -1; 
      } 
      catch 
      { 
       throw; 
      } 

     } 
    } 
관련 문제