简体   繁体   English

如何将变量传递给 SQL 服务器存储过程?

[英]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.到目前为止,我的 WPF 应用程序一直在调用一个简单的“获取所有”存储过程,只是为了让某些东西正常工作,现在它可以工作了。 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 .但是在我的应用程序中,我希望能够将FeedGroupId作为输入变量传递给这个存储过程( FeedGroupId取自 combobox 选择),以便它只返回具有该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:数据访问API:

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

    return output;
}

API Controller: 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. 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}")我不知道这是否是最好的方法,但代码现在可以工作。 My Question has been updated to reflect this.我的问题已更新以反映这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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