.net 我们如何在单个示例中使用存储过程从数据库中删除多个ID?

lf5gs5x2  于 2022-12-05  发布在  .NET
关注(0)|答案(1)|浏览(107)

这是我的存储过程

IF(@mode='DELETE')
        BEGIN
            UPDATE ProjectCostingTypes SET [IsDeleted] = 1, [ModifiedBy] = 1, [ModifiedOn] = GETDATE() 
            WHERE [ProjectCostingTypeId] =@Id 
            SELECT IsDeleted,ProjectCostingTypeId
            FROM ProjectCostingTypes WHERE ProjectCostingTypeId=@Id
        END

下面是我的存储库

public async Task<string> DeleteMultipleProjectCostingTypeByID(List<int> Ids)
        {
            try
            {
                using (var connection = _context.CreateConnection())
                {
                    foreach (int id in Ids)
                    {
                        var parameters = new DynamicParameters();
                        parameters.Add(APIConstants.PARAM_NAME_ID, id);
                        parameters.Add(APIConstants.PARAM_NAME_MODE, APIConstants.PARAM_VALUE_DELETE);
                        parameters.Add(APIConstants.PARAM_NAME_MASTER, APIConstants.PROJECT_COSTING_TYPE);

                        var data = await connection.QuerySingleOrDefaultAsync<ProjectCostingTypes>(APIConstants.DELETE_PROJECT_COSTING_TYPES, parameters, commandType: CommandType.StoredProcedure);

                        // var data = await connection.QueryAsync(APIConstants.DELETE_PROJECT_COSTING_TYPES, parameters, commandType: CommandType.StoredProcedure);
                    }
                    return "Deleted data successfully";
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }

        }
fcg9iug3

fcg9iug31#

One of the ways to achieve this is by adjusting the stored procedure in the following way:
Declare the Id as varchar

@Id varchar(4096)

Adjusting the select statement like:

SELECT IsDeleted,ProjectCostingTypeId FROM ProjectCostingTypes WHERE ProjectCostingTypeId in (' + @Id + ')'

When you call the stored procedure pass the Id(s) as comma separated string like

'5,28'

相关问题