简体   繁体   中英

How to pass a variable to SQL Server stored procedure?

I am new to programming and have been following a tutorial. To this point my WPF application has been calling a simple "get all" stored procedure, just to get something working, and now it does. But in my application, I want to be able to pass a FeedGroupId as an input variable to this stored procedure ( FeedGroupId is taken from a combobox selection) so that it will return only the pens that have that FeedGroupId .

EndPoint:

public async Task<List<FeedGroupPenModel>> GetPensByFeedGroupId(int FeedGroupId)
{
    using (HttpResponseMessage response = await _apiHelper.ApiClient.GetAsync($"/api/FeedGroup/GetPensByFeedGroupId/{FeedGroupId}"))
    {
        if (response.IsSuccessStatusCode)
        {
            var result = await response.Content.ReadAsAsync<List<FeedGroupPenModel>>();
            return result;
        }
        else
        {
            throw new Exception(response.ReasonPhrase);
        }
    }
}

Stored procedure:

CREATE PROCEDURE [dbo].[spFeedGroupPens_GetPensByFeedGroupId]
    @FeedGroupId int
AS
BEGIN
    SET NOCOUNT ON;

    SELECT 
        li.FeedGroupId, li.PenId, li.AsFedPounds, 
        f.RationId, p.PenName           
    FROM
        LotInfo AS li
    INNER JOIN
        FeedGroups AS f ON li.FeedGroupId = f.FeedGroupId
    INNER JOIN
        PenInfo AS p ON li.PenId = p.Id
    WHERE
        li.FeedGroupId = @FeedGroupId
END

Data access API:

public List<FeedGroupPenModel> GetPensByFeedGroupId(int FeedGroupId)
{
    var output = _sql.LoadData<FeedGroupPenModel, dynamic>("dbo.spFeedGroupPens_GetPensByFeedGroupId", new { FeedGroupId } , "The.....Data");

    return output;
}

API Controller:

    [HttpGet("GetPensByFeedGroupId/{FeedGroupId:int}")]
    [Route("GetPensByFeedGroupId")]
    public List<FeedGroupPenModel> GetByFeedGroupId(int FeedGroupId)        
    {
        int feedGroupId = FeedGroupId;
        return _feedGroupPenData.GetPensByFeedGroupId(feedGroupId);
    }

In My controller I specified the argument as part of the url: [HttpGet("GetPensByFeedGroupId/{FeedGroupId:int}")] In the endpoint I passed the argumented as part of the url: .GetAsync($"/api/FeedGroup/GetPensByFeedGroupId/{FeedGroupId}") I don't know if this was the best way, but the code works now. My Question has been updated to reflect this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM