码迷,mamicode.com
首页 > 数据库 > 详细

SQL Procedure Operations

时间:2015-08-07 12:45:20      阅读:124      评论:0      收藏:0      [点我收藏+]

标签:

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

SQL Procedure Operations

标签:

原文地址:http://www.cnblogs.com/Blackeye286/p/4710150.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!