如何使用我传递的参数使存储过程返回“数据集”?

时间:2009-08-28 02:15:37

标签: sql tsql

我对存储过程非常陌生。

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

  

找到我所有的房源   IDCategory等于我的IDCategory   告诉你要找。

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

IDListing,IDCategory,Price,Seller,Image。

我怎么能实现这个目标?

3 个答案:

答案 0 :(得分:5)

要从存储过程填充数据集,您将拥有如下代码:

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);

你的连接字符串会有所不同,有几种不同的方法可以做到这一点,但这应该让你去......一旦你掌握了一些这些,请看看使用声明。它有助于清理资源,并且需要少量代码。这假定存储过程名称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

以下是有关ADO.Net的DataSet及其他项目的链接: http://authors.aspalliance.com/quickstart/howto/doc/adoplus/adoplusoverview.aspx

答案 1 :(得分:2)

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

示例:

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

答案 2 :(得分:2)

整个存储过程:

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 Server参数sniffing issue