您的位置:首页 > 编程语言 > C#

C#操作存储过程,输入参数,返回结果

2007-02-28 15:21 393 查看
SQL存储过程显然是非常强大的,.NET也支持对存储过程的调用,自己尝试着写了个小Sample,因为在SQL的学习中,只是笔记一篇。
环境:WindowXP SP2, VS2005, SQL2005
假定在SQL server上已经存在了NWind数据库,同时有如下的存储过程:(存储过程的功能是根据输入的起始日期和结束日期,返回这个时间段内的销售记录和总销售值,并非本文重点)

1set ANSI_NULLS ON
2set QUOTED_IDENTIFIER ON
3go
4
5
6-- =============================================
7-- Author: <Vitoria Tang>
8-- Create date: <2006.0804>
9-- Description: <It is a sample procedure for get sales record as specific datetime>
-- =============================================
ALTER PROCEDURE [dbo].[User_SalesByYear]
-- Input parameters: Begin date, End date
@BeginDate datetime , @EndDate datetime, @Price int = 0 OUTPUT
AS
BEGIN
--declare @Price money
CREATE TABLE #TempTable
(ID int not null, ProductName nvarchar(40) not null, Price money not null)

INSERT INTO #TempTable(ID, ProductName, Price)
SELECT Orders.OrderID, Products.ProductName, [Order Details].UnitPrice * [Order Details].Discount
FROM Orders, Products, [Order Details]
WHERE (
((Orders.ShippedDate) Is Not Null And
(Orders.ShippedDate) Between @BeginDate And @EndDate)
AND
(Orders.OrderID = [Order Details].OrderID AND [Order Details].ProductID = Products.ProductID)
);

Select * from #TempTable

Select @Price = sum(Price) from [#TempTable]
Print @Price
return (@Price)
END

Sample界面:
private System.Data.SqlClient.SqlConnection _connection = null;
private void InitializeSource()

其次创建执行存储
过程的SqlCommand,当然前后需要打开和关闭数据库连接,调用存储过程需要给SqlCommand的CommandType属性赋值为
CommandType.StoredProcedure,我们的存储过程是有输入和输出参数的,那么在添加到SqlCommand.Prameters
集合中就可以了。如果是输出参数,设置SqlParameter实例的Direction值就可以了,该属性默认值为Input,所以不设置的话,在执行
完后,得不到输出值哦。具体参见下面的代码。

1private SqlCommand GetCommand(object sender, EventArgs e)
2
本文的示例是用SqlDataAdapter来填充了DataSet并把它显示在DataGridView control上,所以接下来,打开数据库连接创建SqlDataAdapter,并填充DataSet吧.

1private void button1_Click(object sender, EventArgs e)
2
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐