【问题标题】:How can I make a stored procedure return a "dataset" using a parameter I pass?如何使用我传递的参数使存储过程返回“数据集”?
【发布时间】:2015-08-06 18:41:12
【问题描述】:

我对存储过程很陌生。

假设我有一个 IDCategory (int),我将它传递给一个存储过程。在正常的谈话中,它会去:

找到我所有的列表 IDCategory 等于我的 IDCategory 告诉你找到。

所以它会找到 3 个列表,并创建一个包含列的表:

IDListing、IDCategory、价格、卖家、图片。

我怎样才能做到这一点?

【问题讨论】:

  • 为什么这个问题用 mysql 和 tsql 标记,因为答案只涉及 mssql?大声笑。

标签: sql tsql


【解决方案1】:

要从存储过程中填充数据集,您需要如下代码:

SqlConnection mySqlConnection =new SqlConnection("server=(local);database=MyDatabase;Integrated Security=SSPI;");

    SqlCommand mySqlCommand = mySqlConnection.CreateCommand();
    mySqlCommand.CommandText = "IDCategory";
    mySqlCommand.CommandType = CommandType.StoredProcedure;
    mySqlCommand.Parameters.Add("@IDCategory", SqlDbType.Int).Value = 5;

    SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter();
    mySqlDataAdapter.SelectCommand = mySqlCommand;
    DataSet myDataSet = new DataSet();
    mySqlConnection.Open();
    mySqlDataAdapter.Fill(myDataSet);

您的连接字符串会有所不同,并且有几种不同的方法可以做到这一点,但这应该会让您继续前进....一旦您掌握了其中的一些,请查看 Using 语句。它有助于清理资源并且需要更少的代码行。这假定存储过程名称 IDCategory 具有一个称为相同的参数。您的设置可能会有所不同。

在这种情况下,您的存储过程将类似于:

CREATE PROC [dbo].[IDCategory] 
    @IDCategory int
AS 
    SELECT IDListing, IDCategory, Price, Seller, Image
         FROM whateveryourtableisnamed
         WHERE IDCategory = @IDCategory

这是存储过程基础知识的链接: http://www.sql-server-performance.com/articles/dba/stored_procedures_basics_p1.aspx

这里是关于 DataSets 和其他 ADO.Net 项目的链接: http://authors.aspalliance.com/quickstart/howto/doc/adoplus/adoplusoverview.aspx

【讨论】:

    【解决方案2】:

    在您的数据库中有一个包含您希望的 5 个字段的表并对其进行查询。

    例子:

    Select IDListing, IDCategory, Price, Seller, Image
    From [listingtable] --whatever your table is called
    where IDCategoryID = @IDCategoryID
    

    【讨论】:

    • 在使用之前声明变量有什么好处? Brisbe42 的答案是否更好,因为它首先声明了变量?
    • 没有存储过程定义的上下文,这个答案更接近于在存储过程中实际使用的内容。
    【解决方案3】:

    整个存储过程:

    CREATE PROCEDURE sp_Listing_Get
      @IDCategory int
    AS
    
      DECLARE @categoryid
          SET @categoryid = @IDCategory
    
    BEGIN
    
       SELECT t.idlisting,
              t.idcategory,
              t.price,
              t.seller,
              t.image
         FROM [databaseName].dbo.LISTING t
        WHERE t.idcategoryid = @categoryid
    
    END
    

    将 [databaseName] 替换为您的数据库名称。使用两个句点格式的好处是,只要执行 sproc 的用户有权访问表(和数据库),sproc 就会返回结果。

    @categoryid 用于处理 SQL Servers 参数sniffing issue

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-14
      • 2023-03-10
      • 1970-01-01
      • 1970-01-01
      • 2015-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多