简体   繁体   English

使用存储过程从查询中获取结果

[英]Get result from query using stored procedure

My program contains a gridview of rows of which I want to check if they are already billed. 我的程序包含一个gridview的行,我想检查它们是否已经计费。

I do this by checking a column in which the ID of the item is stored. 我通过检查存储项目ID的列来做到这一点。

I have the following stored procedure: 我有以下存储过程:

ALTER PROCEDURE [dbo].[getBilledItem]
    @itemID int 
AS
BEGIN

    SET NOCOUNT ON;

    SELECT [items].[dbo].[itemLine].itemID
    FROM [items].[dbo].[itemLine]
    WHERE description LIKE '%' + cast(@itemID AS VARCHAR(255)) + '%'

END

What I want to do in my program is to add the itemID when the stored procedure returns 1 row(s) affected but this doesn't work. 我要在程序中执行的操作是在存储过程返回1 row(s) affected添加itemID,但这行不通。

My code looks like: 我的代码如下:

 using (var conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["Database"].ConnectionString))
                using (var command = new SqlCommand("getBilledItem", conn)
                {
                    CommandType = CommandType.StoredProcedure
                })
                {
                    command.Parameters.Add(new SqlParameter("@itemID", SqlDbType.Int)).Value = itemID;
                    conn.Open();

                    int amount = command.ExecuteNonQuery();

                    if (amount > 0)
                    {
                        AlreadyBilledIDs.Add(itemID.ToString());
                    }
                }

Even when my stored procedure does return a row, my program doesn't catch it. 即使我的存储过程确实返回了一行,程序也不会捕获它。

What in my code am I doing wrong? 我在代码中做错了什么? I thought that CommandExecuteNonQuery would return the amount of affected rows? 我以为CommandExecuteNonQuery会返回受影响的行数? Why isn't this working in my case? 为什么这对我来说不起作用?

What you need is ExecuteScalar method which is used when we have only one row with one column being returned or if we have multiple rows in that case too it will just selected first column of the first row. 您需要的是ExecuteScalar方法,当我们只有一行返回一行时使用该方法,或者在这种情况下也有多行的情况下,它将仅选择第一行的第一列。

So you can do : 所以你可以做:

int amount = Convert.ToInt32(command.ExecuteScalar());

if you need number of rows then you can use Count() in your stored procedure and the c# code will remain same, just modify your query to be: 如果需要行数,则可以在存储过程中使用Count() ,并且c#代码将保持不变,只需将查询修改为:

SELECT Count([items].[dbo].[itemLine].itemID)
.............
.............

now you will have the total number of rows returned by query : 现在您将拥有查询返回的总行数:

int count = Convert.ToInt32(command.ExecuteScalar());

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

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