Hello I’m having trouble displaying the output of a SP in a console window using C#. Here is the SP code first then the C# after that.
(SP code (Updated with SP code))
- GetDepartmentName stored procedure.
IF NOT EXISTS (SELECT * FROM sys.objects
WHERE object_id = OBJECT_ID(N'[dbo].[GetDepartmentName]')
AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[GetDepartmentName]
@ID int,
@Name nvarchar(50) OUTPUT
AS
SELECT @Name = Name FROM Department
WHERE DepartmentID = @ID
'
END
GO
(c# code)
public void RunStoredProcParams()
{
SqlConnection conn = null;
SqlDataReader rdr = null;
int ID = 1;
//string Name = ""; Tried testing with this
try
{
conn = new
SqlConnection("Server=(local);DataBase=School;Integrated Security=SSPI");
conn.Open();
SqlCommand cmd = new SqlCommand("GetDepartmentName", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@ID", ID));
//cmd.Parameters.Add(new SqlParameter("@Name", Name)); Tried testing
//with this. Don't get output when added, get error message when commented out.
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Console.WriteLine("Department: {0}", rdr["Name"]);
}
}
finally
{
if (conn != null)
{
conn.Close();
}
if (rdr != null)
{
rdr.Close();
}
}
}
}
//cmd.Parameters.Add(new SqlParameter("@Name", Name));
I added this line above because I keep getting error message “”Procedure or function ‘GetDepartmentName’ expects parameter ‘@Name’, which was not supplied.” Without an input, I get an error message even though this is suppose to output the results..
You have to add that parameter to the command like you did with id
After you execute the command, you can get the value from
Ok try this then