InputOutput参数类型使用

在《C#调用带返回值的存储过程》一文中介绍了用C#调用带返回值的存储过程,用到了输入参数Input、输出参数Output以及返回值ReturnValue。其实,在.NET中调用存储过程时,还有一种参数类型是InputOutput,参数既能输入,也能输出。今天写了段程序试了一下,了解了具体使用方法。

(1)创建存储过程
USE [AddressList]
GO
/****** 对象: StoredProcedure [dbo].[test] 脚本日期: 12/19/2011 20:23:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[test]
 @GroupName nvarchar(50) output
AS
BEGIN
 select @GroupName=GroupName from ContactGroup where GroupName like '%'+@GroupName+'%'
END
(2)在查询分析器中执行
USE [AddressList]
GO
DECLARE @return_value int,@GroupName nvarchar(50) 
set @GroupName = '老'
EXEC [dbo].[test]
@GroupName output
SELECT @GroupName
(3)编写C#代码调用,指定输入值,并获取输出值
public string SqlParameterInputOutput()
{
    using (SqlConnection conn = new SqlConnection(@"Server=.\sqlexpress;database=AddressList;Integrated Security=True"))
    {
        SqlCommand cmd = new SqlCommand("test", conn);
        cmd.CommandType = CommandType.StoredProcedure;
        SqlParameter p = new SqlParameter("@GroupName", SqlDbType.NVarChar, 50);
        p.Direction = ParameterDirection.InputOutput;
        p.Value="老";
        cmd.Parameters.Add(p);
        conn.Open();
        cmd.ExecuteNonQuery();
        string pValue = p.Value.ToString();
        return pValue;
    }
}

原文地址:https://www.cnblogs.com/zhouhb/p/2293855.html