SqlCommandBuilder.DeriveParameters读取存储过程参数使用示例

用于测试的存储过程:

Create PROCEDURE [dbo].[Do]
    @a int,
    @b int
AS
BEGIN
    return @a + @b
END

测试代码:

using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["SQLServer"].ToString()))
            {
                conn.Open();
                using (SqlCommand cmd = new SqlCommand())
                {
                    cmd.Connection = conn;
                    cmd.CommandText = "Do";
                    cmd.CommandType = CommandType.StoredProcedure;

                    SqlCommandBuilder.DeriveParameters(cmd);
                    cmd.Parameters["@a"].Value = 2;
                    cmd.Parameters["@b"].Value = 3;
                    cmd.ExecuteNonQuery();
                    Console.WriteLine(cmd.Parameters["@RETURN_VALUE"].Value);

                }
                conn.Close();
            }

            Console.ReadKey();
        }
    }
}

说明:SqlCommandBuilder.DeriveParameters读取存储过程参数填充到SqlCommand.Parameters集合,集合第一项参数名总是@RETURN_VALUE!

评论: 0 | 引用: 0 | 查看次数: 3626
发表评论
登录后再发表评论!