SQL Procedure Operations

本文介绍了一个用于处理SQL存储过程的实用类SQLHelper,包括检查存储过程是否存在、创建存储过程及通过C#执行存储过程的方法。提供了ProcedureIsExist、CreateProcedure和ExecuteProcedure三个核心功能。

This Class is used to handle SQL procedures, including Verify SP exist or not, Create SP into DB and Execute SP via C#.

using System;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace SqlBIS.Auto.Framework
{
    public class SqlHelper
    {
        public string ConnString { get; set; }
        public SqlConnection Connection { get; set; }

        public SqlHelper(string connString)
        {
            this.ConnString = connString;
            Connection = new SqlConnection(connString);
        }

        /// <summary>
        /// Verify if DB contain procedure or not
        /// </summary>
        /// <param name="proName">procedure name</param>
        /// <returns></returns>
        public  bool ProcedureIsExist(string proName)
        {
            bool result = false;
            String sqlComm = String.Format("IF OBJECT_ID('{0}') IS NOT NULL SELECT 'true' ELSE SELECT 'false'", proName);
            
            SqlCommand cmd = new SqlCommand(sqlComm, this.Connection);
            cmd.CommandType = CommandType.Text;
            this.Connection.Open();
            result = Convert.ToBoolean((cmd.ExecuteScalar()).ToString());
            this.Connection.Close();

            return result;
        }

        /// <summary>
        /// Create a new procedure
        /// </summary>
        /// <param name="proName"></param>
        /// <param name="proCommand"></param>
        public  void CreateProcedure(string proName, string proCommand)
        {
            SqlCommand cmd = new SqlCommand(proCommand, this.Connection);
            Connection.Open();
            cmd.CommandType = CommandType.Text;
            cmd.ExecuteNonQuery();
            Connection.Close();
        }

        /// <summary>
        /// Execute procedure and return DataTable
        /// </summary>
        /// <param name="proName"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public DataTable ExecuteProcedure(string proName, SqlParameter[] parameters)
        {
            DataTable dt = new DataTable();

            SqlCommand cmd = new SqlCommand(proName, this.Connection);
            cmd.CommandType = System.Data.CommandType.StoredProcedure;
            foreach (var item in parameters)
                cmd.Parameters.Add(item);
            SqlDataAdapter sa = new SqlDataAdapter(cmd);
            sa.Fill(dt);

            return dt;
        }
    }
}

转载于:https://www.cnblogs.com/Blackeye286/p/4710150.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值