将参数传递给存储过程

时间:2014-05-14 15:12:28

标签: sqlparameter sql-parametrized-query

我想将参数传递给此存储过程:

ALTER PROCEDURE [USP_SelectProject]
-- Add the parameters for the stored procedure here

@ProjectNumber as int

AS
BEGIN
if @ProjectNumber is null 
begin
select * from tbl_projects
end
else
begin
SELECT * from tbl_projects where ProjectID = @ProjectNumber
end
End

这是.net代码

SqlConnection PTConn = new SqlConnection(ConfigurationManager.ConnectionStrings["Project_Tracker"].ConnectionString);
SqlCommand PTCmd = new SqlCommand("USP_SelectProject", PTConn);
PTCmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter PTda = new SqlDataAdapter(PTCmd);
PTda.SelectCommand.Parameters["@ProjectNumber"].Value = DBNull.Value;
DataSet PTds = new DataSet();
PTda.Fill(PTds);

        GridView1.DataSource = PTds;
        GridView1.DataBind();

我收到以下错误:此参数不包含带有ParameterName' @ ProjectNumber'的SqlParameter

1 个答案:

答案 0 :(得分:0)

您必须先Add()参数。

SqlParameter p = PTda.SelectCommand.Parameters.Add("@ProjectNumber", DbType.Int);
p.Value = DBNull.Value;