如何将int数组传递给存储过程然后选择id在该数组中的所有位置

时间:2018-02-15 08:20:50

标签: c# sql stored-procedures asp.net-web-api

我正在创建一个web api方法,我可以在给定的类别ID列表中选择所有产品作为参数

c#方法将是:

        [Route("api/products/search")]
        public HttpResponseMessage SearchProducts([FromUri] int[] categoryIds)
        {
        DataSet ds = new DataSet();
        using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings[connection_string].ConnectionString))
        {
            SqlCommand cmd = new SqlCommand("sp_search_product_by_category", con);
            cmd.Parameters.AddWithValue("category_ids", categoryIds);
            cmd.CommandType = CommandType.StoredProcedure;

            con.Open();
            SqlDataAdapter adp = new SqlDataAdapter();
            adp.SelectCommand = cmd;
            adp.Fill(ds);
        }

        var message = Request.CreateResponse(HttpStatusCode.OK, ds.Tables[0]);
        return message;
        }

然后sp将是:

CREATE PROCEDURE [dbo].[sp_search_product_by_category] 
    -- Add the parameters for the stored procedure here
    @category_ids [some_array_data_type] <-- what should be in here?
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- Select statements for procedure here
    SELECT * from products where category in @category_ids
END

我如何让SP知道它的数组,并使其适当选择?

任何帮助将不胜感激

0 个答案:

没有答案