• MSSQL数据库C#操作类(SQLHELPER类的修改版)


    1. using System;   
    2. using System.Collections;   
    3. using System.Collections.Specialized;   
    4. using System.Data;   
    5. using System.Data.SqlClient;   
    6. using System.Configuration;   
    7. namespace NMJU.Web.DBUtility   
    8. {   
    9.     /// <summary>   
    10.     /// 数据访问抽象基础类(MSSQL)   
    11.     /// Copyright (C) 2004-2008 NMJU.NET   
    12.     /// All rights reserved   
    13.     /// </summary>   
    14.     public abstract class DbHelperSQL   
    15.     {   
    16.         //数据库连接字符串(web.config来配置)   
    17.         public static string connectionString = ConfigurationManager.AppSettings["MSSQLConnectionString"];   
    18.         //    public static string connectionString = LemonJu.Common.DEncrypt.DESEncrypt.Decrypt(LemonJu.Common.ConfigHelper.GetConfigString("ConnectionString"));   
    19.         public DbHelperSQL()   
    20.         {   
    21.         }  
    22.  
    23.         #region 公用方法   
    24.         /// <summary>   
    25.         /// 获取某个表的数量   
    26.         /// </summary>   
    27.         /// <param name="field">主键</param>   
    28.         /// <param name="tableName">表名</param>   
    29.         /// <param name="where">条件</param>   
    30.         /// <returns></returns>   
    31.         public static int GetDataRecordCount(string field, string tableName, string where)   
    32.         {   
    33.   
    34.   
    35.             string strsql = "select count(" + field + ") from " + tableName;   
    36.             if (where != "")   
    37.             {   
    38.                 strsql += " where " + where;   
    39.             }   
    40.             object obj = DbHelperSQL.GetSingle(strsql);   
    41.             if (obj == null)   
    42.             {   
    43.                 return 1;   
    44.             }   
    45.             else  
    46.             {   
    47.                 return int.Parse(obj.ToString());   
    48.             }   
    49.   
    50.   
    51.         }   
    52.         public static int GetMaxID(string FieldName, string TableName)   
    53.         {   
    54.             string strsql = "select max(" + FieldName + ")+1 from " + TableName;   
    55.             object obj = DbHelperSQL.GetSingle(strsql);   
    56.             if (obj == null)   
    57.             {   
    58.                 return 1;   
    59.             }   
    60.             else  
    61.             {   
    62.                 return int.Parse(obj.ToString());   
    63.             }   
    64.         }   
    65.         public static bool Exists(string strSql)   
    66.         {   
    67.             object obj = DbHelperSQL.GetSingle(strSql);   
    68.             int cmdresult;   
    69.             if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))   
    70.             {   
    71.                 cmdresult = 0;   
    72.             }   
    73.             else  
    74.             {   
    75.                 cmdresult = int.Parse(obj.ToString());   
    76.             }   
    77.             if (cmdresult == 0)   
    78.             {   
    79.                 return false;   
    80.             }   
    81.             else  
    82.             {   
    83.                 return true;   
    84.             }   
    85.         }   
    86.         public static bool Exists(string strSql, params SqlParameter[] cmdParms)   
    87.         {   
    88.             object obj = DbHelperSQL.GetSingle(strSql, cmdParms);   
    89.             int cmdresult;   
    90.             if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))   
    91.             {   
    92.                 cmdresult = 0;   
    93.             }   
    94.             else  
    95.             {   
    96.                 cmdresult = int.Parse(obj.ToString());   
    97.             }   
    98.             if (cmdresult == 0)   
    99.             {   
    100.                 return false;   
    101.             }   
    102.             else  
    103.             {   
    104.                 return true;   
    105.             }   
    106.         }  
    107.         #endregion  
    108.  
    109.         #region  执行简单SQL语句   
    110.   
    111.         /// <summary>   
    112.         /// 执行SQL语句,返回影响的记录数   
    113.         /// </summary>   
    114.         /// <param name="SQLString">SQL语句</param>   
    115.         /// <returns>影响的记录数</returns>   
    116.         public static int ExecuteSql(string SQLString)   
    117.         {   
    118.             using (SqlConnection connection = new SqlConnection(connectionString))   
    119.             {   
    120.                 using (SqlCommand cmd = new SqlCommand(SQLString, connection))   
    121.                 {   
    122.                     try  
    123.                     {   
    124.                         connection.Open();   
    125.                         int rows = cmd.ExecuteNonQuery();   
    126.                         return rows;   
    127.                     }   
    128.                     catch (System.Data.SqlClient.SqlException E)   
    129.                     {   
    130.                         connection.Close();   
    131.                         throw new Exception(E.Message);   
    132.                         //ITNB.Base.Error.showError(E.Message.ToString());   
    133.                     }   
    134.                 }   
    135.             }   
    136.         }   
    137.   
    138.         /// <summary>   
    139.         /// 执行SQL语句,设置命令的执行等待时间   
    140.         /// </summary>   
    141.         /// <param name="SQLString"></param>   
    142.         /// <param name="Times"></param>   
    143.         /// <returns></returns>   
    144.         public static int ExecuteSqlByTime(string SQLString, int Times)   
    145.         {   
    146.             using (SqlConnection connection = new SqlConnection(connectionString))   
    147.             {   
    148.                 using (SqlCommand cmd = new SqlCommand(SQLString, connection))   
    149.                 {   
    150.                     try  
    151.                     {   
    152.                         connection.Open();   
    153.                         cmd.CommandTimeout = Times;   
    154.                         int rows = cmd.ExecuteNonQuery();   
    155.                         return rows;   
    156.                     }   
    157.                     catch (System.Data.SqlClient.SqlException E)   
    158.                     {   
    159.                         connection.Close();   
    160.                         throw new Exception(E.Message);   
    161.                         // ITNB.Base.Error.showError(E.Message.ToString());   
    162.                     }   
    163.                 }   
    164.             }   
    165.         }   
    166.   
    167.         /// <summary>   
    168.         /// 执行多条SQL语句,实现数据库事务。   
    169.         /// </summary>   
    170.         /// <param name="SQLStringList">多条SQL语句</param>        
    171.         public static void ExecuteSqlTran(ArrayList SQLStringList)   
    172.         {   
    173.             using (SqlConnection conn = new SqlConnection(connectionString))   
    174.             {   
    175.                 conn.Open();   
    176.                 SqlCommand cmd = new SqlCommand();   
    177.                 cmd.Connection = conn;   
    178.                 SqlTransaction tx = conn.BeginTransaction();   
    179.                 cmd.Transaction = tx;   
    180.                 try  
    181.                 {   
    182.                     for (int n = 0; n < SQLStringList.Count; n++)   
    183.                     {   
    184.                         string strsql = SQLStringList[n].ToString();   
    185.                         if (strsql.Trim().Length > 1)   
    186.                         {   
    187.                             cmd.CommandText = strsql;   
    188.                             cmd.ExecuteNonQuery();   
    189.                         }   
    190.                     }   
    191.                     tx.Commit();   
    192.                 }   
    193.                 catch (System.Data.SqlClient.SqlException E)   
    194.                 {   
    195.                     tx.Rollback();   
    196.                     throw new Exception(E.Message);   
    197.                     //    ITNB.Base.Error.showError(E.Message.ToString());   
    198.                 }   
    199.             }   
    200.         }   
    201.         /// <summary>   
    202.         /// 执行带一个存储过程参数的的SQL语句。   
    203.         /// </summary>   
    204.         /// <param name="SQLString">SQL语句</param>   
    205.         /// <param name="content">参数内容,比如一个字段是格式复杂的文章,有特殊符号,可以通过这个方式添加</param>   
    206.         /// <returns>影响的记录数</returns>   
    207.         public static int ExecuteSql(string SQLString, string content)   
    208.         {   
    209.             using (SqlConnection connection = new SqlConnection(connectionString))   
    210.             {   
    211.                 SqlCommand cmd = new SqlCommand(SQLString, connection);   
    212.                 System.Data.SqlClient.SqlParameter myParameter = new System.Data.SqlClient.SqlParameter("@content", SqlDbType.NText);   
    213.                 myParameter.Value = content;   
    214.                 cmd.Parameters.Add(myParameter);   
    215.                 try  
    216.                 {   
    217.                     connection.Open();   
    218.                     int rows = cmd.ExecuteNonQuery();   
    219.                     return rows;   
    220.                 }   
    221.                 catch (System.Data.SqlClient.SqlException E)   
    222.                 {   
    223.                     throw new Exception(E.Message);   
    224.                     //   ITNB.Base.Error.showError(E.Message.ToString());   
    225.                 }   
    226.                 finally  
    227.                 {   
    228.                     cmd.Dispose();   
    229.                     connection.Close();   
    230.                 }   
    231.             }   
    232.         }   
    233.         /// <summary>   
    234.         /// 执行带一个存储过程参数的的SQL语句。   
    235.         /// </summary>   
    236.         /// <param name="SQLString">SQL语句</param>   
    237.         /// <param name="content">参数内容,比如一个字段是格式复杂的文章,有特殊符号,可以通过这个方式添加</param>   
    238.         /// <returns>影响的记录数</returns>   
    239.         public static object ExecuteSqlGet(string SQLString, string content)   
    240.         {   
    241.             using (SqlConnection connection = new SqlConnection(connectionString))   
    242.             {   
    243.                 SqlCommand cmd = new SqlCommand(SQLString, connection);   
    244.                 System.Data.SqlClient.SqlParameter myParameter = new System.Data.SqlClient.SqlParameter("@content", SqlDbType.NText);   
    245.                 myParameter.Value = content;   
    246.                 cmd.Parameters.Add(myParameter);   
    247.                 try  
    248.                 {   
    249.                     connection.Open();   
    250.                     object obj = cmd.ExecuteScalar();   
    251.                     if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))   
    252.                     {   
    253.                         return null;   
    254.                     }   
    255.                     else  
    256.                     {   
    257.                         return obj;   
    258.                     }   
    259.                 }   
    260.                 catch (System.Data.SqlClient.SqlException E)   
    261.                 {   
    262.                     throw new Exception(E.Message);   
    263.                     // ITNB.Base.Error.showError(E.Message.ToString());   
    264.                 }   
    265.                 finally  
    266.                 {   
    267.                     cmd.Dispose();   
    268.                     connection.Close();   
    269.                 }   
    270.             }   
    271.         }   
    272.         /// <summary>   
    273.         /// 向数据库里插入图像格式的字段(和上面情况类似的另一种实例)   
    274.         /// </summary>   
    275.         /// <param name="strSQL">SQL语句</param>   
    276.         /// <param name="fs">图像字节,数据库的字段类型为image的情况</param>   
    277.         /// <returns>影响的记录数</returns>   
    278.         public static int ExecuteSqlInsertImg(string strSQL, byte[] fs)   
    279.         {   
    280.             using (SqlConnection connection = new SqlConnection(connectionString))   
    281.             {   
    282.                 SqlCommand cmd = new SqlCommand(strSQL, connection);   
    283.                 System.Data.SqlClient.SqlParameter myParameter = new System.Data.SqlClient.SqlParameter("@fs", SqlDbType.Image);   
    284.                 myParameter.Value = fs;   
    285.                 cmd.Parameters.Add(myParameter);   
    286.                 try  
    287.                 {   
    288.                     connection.Open();   
    289.                     int rows = cmd.ExecuteNonQuery();   
    290.                     return rows;   
    291.                 }   
    292.                 catch (System.Data.SqlClient.SqlException E)   
    293.                 {   
    294.                     throw new Exception(E.Message);   
    295.                     //ITNB.Base.Error.showError(E.Message.ToString());   
    296.                 }   
    297.                 finally  
    298.                 {   
    299.                     cmd.Dispose();   
    300.                     connection.Close();   
    301.                 }   
    302.             }   
    303.         }   
    304.   
    305.         /// <summary>   
    306.         /// 执行一条计算查询结果语句,返回查询结果(object)。   
    307.         /// </summary>   
    308.         /// <param name="SQLString">计算查询结果语句</param>   
    309.         /// <returns>查询结果(object)</returns>   
    310.         public static object GetSingle(string SQLString)   
    311.         {   
    312.             using (SqlConnection connection = new SqlConnection(connectionString))   
    313.             {   
    314.                 using (SqlCommand cmd = new SqlCommand(SQLString, connection))   
    315.                 {   
    316.                     try  
    317.                     {   
    318.                         connection.Open();   
    319.                         object obj = cmd.ExecuteScalar();   
    320.                         if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))   
    321.                         {   
    322.                             return null;   
    323.                         }   
    324.                         else  
    325.                         {   
    326.                             return obj;   
    327.                         }   
    328.                     }   
    329.                     catch (System.Data.SqlClient.SqlException e)   
    330.                     {   
    331.                         connection.Close();   
    332.                         throw new Exception(e.Message);   
    333.                         //  ITNB.Base.Error.showError(e.Message.ToString());   
    334.                     }   
    335.                 }   
    336.             }   
    337.         }   
    338.   
    339.   
    340.         /// <summary>   
    341.         /// 执行查询语句,返回SqlDataReader(使用该方法切记要手工关闭SqlDataReader和连接)   
    342.         /// </summary>   
    343.         /// <param name="strSQL">查询语句</param>   
    344.         /// <returns>SqlDataReader</returns>   
    345.         public static SqlDataReader ExecuteReader(string strSQL)   
    346.         {   
    347.             SqlConnection connection = new SqlConnection(connectionString);   
    348.             SqlCommand cmd = new SqlCommand(strSQL, connection);   
    349.             try  
    350.             {   
    351.                 connection.Open();   
    352.                 SqlDataReader myReader = cmd.ExecuteReader();   
    353.                 return myReader;   
    354.             }   
    355.             catch (System.Data.SqlClient.SqlException e)   
    356.             {   
    357.                 throw new Exception(e.Message);   
    358.                 // ITNB.Base.Error.showError(e.Message.ToString());   
    359.             }   
    360.             //finally //不能在此关闭,否则,返回的对象将无法使用   
    361.             //{   
    362.             //  cmd.Dispose();   
    363.             //  connection.Close();   
    364.             //}    
    365.   
    366.   
    367.         }   
    368.         /// <summary>   
    369.         /// 执行查询语句,返回DataSet   
    370.         /// </summary>   
    371.         /// <param name="SQLString">查询语句</param>   
    372.         /// <returns>DataSet</returns>   
    373.         public static DataSet Query(string SQLString)   
    374.         {   
    375.             using (SqlConnection connection = new SqlConnection(connectionString))   
    376.             {   
    377.                 DataSet ds = new DataSet();   
    378.                 try  
    379.                 {   
    380.                     connection.Open();   
    381.                     SqlDataAdapter command = new SqlDataAdapter(SQLString, connection);   
    382.                     command.Fill(ds, "ds");   
    383.                 }   
    384.                 catch (System.Data.SqlClient.SqlException E)   
    385.                 {   
    386.                     throw new Exception(E.Message);   
    387.                     //   ITNB.Base.Error.showError(E.Message.ToString());   
    388.                 }   
    389.                 return ds;   
    390.             }   
    391.         }   
    392.         /// <summary>   
    393.         /// 执行查询语句,返回DataSet,设置命令的执行等待时间   
    394.         /// </summary>   
    395.         /// <param name="SQLString"></param>   
    396.         /// <param name="Times"></param>   
    397.         /// <returns></returns>   
    398.         public static DataSet Query(string SQLString, int Times)   
    399.         {   
    400.             using (SqlConnection connection = new SqlConnection(connectionString))   
    401.             {   
    402.                 DataSet ds = new DataSet();   
    403.                 try  
    404.                 {   
    405.                     connection.Open();   
    406.                     SqlDataAdapter command = new SqlDataAdapter(SQLString, connection);   
    407.                     command.SelectCommand.CommandTimeout = Times;   
    408.                     command.Fill(ds, "ds");   
    409.                 }   
    410.                 catch (System.Data.SqlClient.SqlException E)   
    411.                 {   
    412.                     throw new Exception(E.Message);   
    413.                     //  ITNB.Base.Error.showError(ex.Message.ToString());   
    414.                 }   
    415.                 return ds;   
    416.             }   
    417.         }  
    418.  
    419.  
    420.  
    421.         #endregion  
    422.  
    423.         #region 执行带参数的SQL语句   
    424.   
    425.         /// <summary>   
    426.         /// 执行SQL语句,返回影响的记录数   
    427.         /// </summary>   
    428.         /// <param name="SQLString">SQL语句</param>   
    429.         /// <returns>影响的记录数</returns>   
    430.         public static int ExecuteSql(string SQLString, params SqlParameter[] cmdParms)   
    431.         {   
    432.             using (SqlConnection connection = new SqlConnection(connectionString))   
    433.             {   
    434.                 using (SqlCommand cmd = new SqlCommand())   
    435.                 {   
    436.                     try  
    437.                     {   
    438.                         PrepareCommand(cmd, connection, null, SQLString, cmdParms);   
    439.                         int rows = cmd.ExecuteNonQuery();   
    440.                         cmd.Parameters.Clear();   
    441.                         return rows;   
    442.                     }   
    443.                     catch (System.Data.SqlClient.SqlException E)   
    444.                     {   
    445.                         throw new Exception(E.Message);   
    446.                         //  ITNB.Base.Error.showError(E.Message.ToString());   
    447.                     }   
    448.                 }   
    449.             }   
    450.         }   
    451.   
    452.   
    453.         /// <summary>   
    454.         /// 执行多条SQL语句,实现数据库事务。   
    455.         /// </summary>   
    456.         /// <param name="SQLStringList">SQL语句的哈希表(key为sql语句,value是该语句的SqlParameter[])</param>   
    457.         public static void ExecuteSqlTran(Hashtable SQLStringList)   
    458.         {   
    459.             using (SqlConnection conn = new SqlConnection(connectionString))   
    460.             {   
    461.                 conn.Open();   
    462.                 using (SqlTransaction trans = conn.BeginTransaction())   
    463.                 {   
    464.                     SqlCommand cmd = new SqlCommand();   
    465.                     try  
    466.                     {   
    467.                         //循环   
    468.                         foreach (DictionaryEntry myDE in SQLStringList)   
    469.                         {   
    470.                             string cmdText = myDE.Key.ToString();   
    471.                             SqlParameter[] cmdParms = (SqlParameter[])myDE.Value;   
    472.                             PrepareCommand(cmd, conn, trans, cmdText, cmdParms);   
    473.                             int val = cmd.ExecuteNonQuery();   
    474.                             cmd.Parameters.Clear();   
    475.   
    476.                             trans.Commit();   
    477.                         }   
    478.                     }   
    479.                     catch  
    480.                     {   
    481.                         trans.Rollback();   
    482.                         throw;   
    483.                     }   
    484.                 }   
    485.             }   
    486.         }   
    487.   
    488.   
    489.         /// <summary>   
    490.         /// 执行一条计算查询结果语句,返回查询结果(object)。   
    491.         /// </summary>   
    492.         /// <param name="SQLString">计算查询结果语句</param>   
    493.         /// <returns>查询结果(object)</returns>   
    494.         public static object GetSingle(string SQLString, params SqlParameter[] cmdParms)   
    495.         {   
    496.             using (SqlConnection connection = new SqlConnection(connectionString))   
    497.             {   
    498.                 using (SqlCommand cmd = new SqlCommand())   
    499.                 {   
    500.                     try  
    501.                     {   
    502.                         PrepareCommand(cmd, connection, null, SQLString, cmdParms);   
    503.                         object obj = cmd.ExecuteScalar();   
    504.                         cmd.Parameters.Clear();   
    505.                         if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))   
    506.                         {   
    507.                             return null;   
    508.                         }   
    509.                         else  
    510.                         {   
    511.                             return obj;   
    512.                         }   
    513.                     }   
    514.                     catch (System.Data.SqlClient.SqlException e)   
    515.                     {   
    516.                         throw new Exception(e.Message);   
    517.                         // ITNB.Base.Error.showError(e.Message.ToString());   
    518.                     }   
    519.                 }   
    520.             }   
    521.         }   
    522.   
    523.         /// <summary>   
    524.         /// 执行查询语句,返回SqlDataReader (使用该方法切记要手工关闭SqlDataReader和连接)   
    525.         /// </summary>   
    526.         /// <param name="strSQL">查询语句</param>   
    527.         /// <returns>SqlDataReader</returns>   
    528.         public static SqlDataReader ExecuteReader(string SQLString, params SqlParameter[] cmdParms)   
    529.         {   
    530.             SqlConnection connection = new SqlConnection(connectionString);   
    531.             SqlCommand cmd = new SqlCommand();   
    532.             try  
    533.             {   
    534.                 PrepareCommand(cmd, connection, null, SQLString, cmdParms);   
    535.                 SqlDataReader myReader = cmd.ExecuteReader();   
    536.                 cmd.Parameters.Clear();   
    537.                 return myReader;   
    538.             }   
    539.             catch (System.Data.SqlClient.SqlException e)   
    540.             {   
    541.                 throw new Exception(e.Message);   
    542.                 // ITNB.Base.Error.showError(e.Message.ToString());   
    543.             }   
    544.             //finally //不能在此关闭,否则,返回的对象将无法使用   
    545.             //{   
    546.             //  cmd.Dispose();   
    547.             //  connection.Close();   
    548.             //}    
    549.   
    550.         }   
    551.   
    552.         /// <summary>   
    553.         /// 执行查询语句,返回DataSet   
    554.         /// </summary>   
    555.         /// <param name="SQLString">查询语句</param>   
    556.         /// <returns>DataSet</returns>   
    557.         public static DataSet Query(string SQLString, params SqlParameter[] cmdParms)   
    558.         {   
    559.             using (SqlConnection connection = new SqlConnection(connectionString))   
    560.             {   
    561.                 SqlCommand cmd = new SqlCommand();   
    562.                 PrepareCommand(cmd, connection, null, SQLString, cmdParms);   
    563.                 using (SqlDataAdapter da = new SqlDataAdapter(cmd))   
    564.                 {   
    565.                     DataSet ds = new DataSet();   
    566.                     try  
    567.                     {   
    568.                         da.Fill(ds, "ds");   
    569.                         cmd.Parameters.Clear();   
    570.                     }   
    571.                     catch (System.Data.SqlClient.SqlException E)   
    572.                     {   
    573.                         throw new Exception(E.Message);   
    574.                         //  ITNB.Base.Error.showError(ex.Message.ToString());   
    575.                     }   
    576.                     return ds;   
    577.                 }   
    578.             }   
    579.         }   
    580.   
    581.   
    582.         private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, string cmdText, SqlParameter[] cmdParms)   
    583.         {   
    584.             if (conn.State != ConnectionState.Open)   
    585.                 conn.Open();   
    586.             cmd.Connection = conn;   
    587.             cmd.CommandText = cmdText;   
    588.             if (trans != null)   
    589.                 cmd.Transaction = trans;   
    590.             cmd.CommandType = CommandType.Text;//cmdType;   
    591.             if (cmdParms != null)   
    592.             {   
    593.   
    594.   
    595.                 foreach (SqlParameter parameter in cmdParms)   
    596.                 {   
    597.                     if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) &&   
    598.                         (parameter.Value == null))   
    599.                     {   
    600.                         parameter.Value = DBNull.Value;   
    601.                     }   
    602.                     cmd.Parameters.Add(parameter);   
    603.                 }   
    604.             }   
    605.         }  
    606.  
    607.         #endregion  
    608.  
    609.         #region 存储过程操作   
    610.   
    611.         /// <summary>   
    612.         /// 执行存储过程  (使用该方法切记要手工关闭SqlDataReader和连接)   
    613.         /// </summary>   
    614.         /// <param name="storedProcName">存储过程名</param>   
    615.         /// <param name="parameters">存储过程参数</param>   
    616.         /// <returns>SqlDataReader</returns>   
    617.         public static SqlDataReader RunProcedure(string storedProcName, IDataParameter[] parameters)   
    618.         {   
    619.             SqlConnection connection = new SqlConnection(connectionString);   
    620.             SqlDataReader returnReader;   
    621.             connection.Open();   
    622.             SqlCommand command = BuildQueryCommand(connection, storedProcName, parameters);   
    623.             command.CommandType = CommandType.StoredProcedure;   
    624.             returnReader = command.ExecuteReader();   
    625.             //Connection.Close(); 不能在此关闭,否则,返回的对象将无法使用               
    626.             return returnReader;   
    627.   
    628.         }   
    629.   
    630.   
    631.         /// <summary>   
    632.         /// 执行存储过程   
    633.         /// </summary>   
    634.         /// <param name="storedProcName">存储过程名</param>   
    635.         /// <param name="parameters">存储过程参数</param>   
    636.         /// <param name="tableName">DataSet结果中的表名</param>   
    637.         /// <returns>DataSet</returns>   
    638.         public static DataSet RunProcedure(string storedProcName, IDataParameter[] parameters, string tableName)   
    639.         {   
    640.             using (SqlConnection connection = new SqlConnection(connectionString))   
    641.             {   
    642.                 DataSet dataSet = new DataSet();   
    643.                 connection.Open();   
    644.                 SqlDataAdapter sqlDA = new SqlDataAdapter();   
    645.                 sqlDA.SelectCommand = BuildQueryCommand(connection, storedProcName, parameters);   
    646.                 sqlDA.Fill(dataSet, tableName);   
    647.                 connection.Close();   
    648.                 return dataSet;   
    649.             }   
    650.         }   
    651.         public static DataSet RunProcedure(string storedProcName, IDataParameter[] parameters, string tableName, int Times)   
    652.         {   
    653.             using (SqlConnection connection = new SqlConnection(connectionString))   
    654.             {   
    655.                 DataSet dataSet = new DataSet();   
    656.                 connection.Open();   
    657.                 SqlDataAdapter sqlDA = new SqlDataAdapter();   
    658.                 sqlDA.SelectCommand = BuildQueryCommand(connection, storedProcName, parameters);   
    659.                 sqlDA.SelectCommand.CommandTimeout = Times;   
    660.                 sqlDA.Fill(dataSet, tableName);   
    661.                 connection.Close();   
    662.                 return dataSet;   
    663.             }   
    664.         }   
    665.         /// <summary>   
    666.         /// 执行存储过程后返回执行结果(标识)   
    667.         /// </summary>   
    668.         /// <param name="storedProcName"></param>   
    669.         /// <param name="parameters"></param>   
    670.         /// <returns></returns>   
    671.         public static string RunProcedureState(string storedProcName, IDataParameter[] parameters)   
    672.         {   
    673.             using (SqlConnection connection = new SqlConnection(connectionString))   
    674.             {   
    675.   
    676.                 connection.Open();   
    677.                 SqlDataAdapter sqlDA = new SqlDataAdapter();   
    678.                 sqlDA.SelectCommand = BuildQueryCommand(connection, storedProcName, parameters);   
    679.                 sqlDA.SelectCommand.Parameters.Add(new SqlParameter("ReturnValue", SqlDbType.Int, 4, ParameterDirection.ReturnValue, false, 0, 0, string.Empty, DataRowVersion.Default, null)); //增加存储过程的返回值参数   
    680.                 sqlDA.SelectCommand.ExecuteNonQuery();   
    681.                 connection.Close();   
    682.                 return sqlDA.SelectCommand.Parameters["ReturnValue"].Value.ToString();   
    683.             }   
    684.         }   
    685.         /*  
    686. @TableNames VARCHAR(200),    --表名,可以是多个表,但不能用别名  
    687. @PrimaryKey VARCHAR(100),    --主键,可以为空,但@Order为空时该值不能为空  
    688. @Fields    VARCHAR(200),        --要取出的字段,可以是多个表的字段,可以为空,为空表示select *  
    689. @PageSize INT,            --每页记录数  
    690. @CurrentPage INT,        --当前页,0表示第1页  
    691. @Filter VARCHAR(200) = '',    --条件,可以为空,不用填 where  
    692. @Group VARCHAR(200) = '',    --分组依据,可以为空,不用填 group by  
    693. @Order VARCHAR(200) = ''    --排序,可以为空,为空默认按主键升序排列,不用填 order by  
    694.  
    695.          */  
    696.         /// <summary>   
    697.         /// 关键字,显示字段,表,条件,排序,每页显示数,当前页   
    698.         /// </summary>   
    699.         /// <param name="PrimaryKey">主键</param>   
    700.         /// <param name="Fields">要取出的字段</param>   
    701.         /// <param name="TableNames">表名</param>   
    702.         /// <param name="Filter">条件</param>   
    703.         /// <param name="Order">排序</param>   
    704.         /// <param name="PageSize">每页记录数INT</param>   
    705.         /// <param name="CurrentPage">当前页,INT</param>   
    706.         /// <returns></returns>   
    707.         public static DataSet GetPageDataList(string PrimaryKey, string Fields, string TableNames, string Filter, string Order, int PageSize, int CurrentPage)   
    708.         {   
    709.             string tableName = "viewPage";   
    710.             string storedProcName = "P_viewPage";   
    711.             IDataParameter[] p = new IDataParameter[8];   
    712.             p[0] = new SqlParameter("TableNames", TableNames);   
    713.             p[1] = new SqlParameter("PrimaryKey", PrimaryKey);   
    714.             p[2] = new SqlParameter("Fields", Fields);   
    715.             p[3] = new SqlParameter("PageSize", PageSize);   
    716.             p[4] = new SqlParameter("CurrentPage", CurrentPage - 1);   
    717.             p[5] = new SqlParameter("Filter", Filter);   
    718.             p[6] = new SqlParameter("Group""");   
    719.             p[7] = new SqlParameter("Order", Order);   
    720.   
    721.             return RunProcedure(storedProcName, p, tableName);   
    722.         }   
    723.         public static DataSet GetPageDataList(string PrimaryKey, string Fields, string TableNames, string Filter, string Order, int PageSize, int CurrentPage, string Group)   
    724.         {   
    725.             string tableName = "viewPage";   
    726.             string storedProcName = "P_viewPage";   
    727.             IDataParameter[] p = new IDataParameter[8];   
    728.             p[0] = new SqlParameter("TableNames", TableNames);   
    729.             p[1] = new SqlParameter("PrimaryKey", PrimaryKey);   
    730.             p[2] = new SqlParameter("Fields", Fields);   
    731.             p[3] = new SqlParameter("PageSize", PageSize);   
    732.             p[4] = new SqlParameter("CurrentPage", CurrentPage - 1);   
    733.             p[5] = new SqlParameter("Filter", Filter);   
    734.             p[6] = new SqlParameter("Group", Group);   
    735.             p[7] = new SqlParameter("Order", Order);   
    736.   
    737.             return RunProcedure(storedProcName, p, tableName);   
    738.         }   
    739.         /*  
    740. @TableName VARCHAR(200),     --表名  
    741. @FieldList VARCHAR(2000),    --显示列名,如果是全部字段则为*  
    742. @PrimaryKey VARCHAR(100),    --单一主键或唯一值键  
    743. @Where VARCHAR(2000),        --查询条件 不含'where'字符,如id>10 and len(userid)>9  
    744. @Order VARCHAR(1000),        --排序 不含'order by'字符,如id asc,userid desc,必须指定asc或desc  
    745. --注意当@SortType=3时生效,记住一定要在最后加上主键,否则会让你比较郁闷  
    746. @SortType INT,               --排序规则 1:正序asc 2:倒序desc 3:多列排序方法  
    747. @RecorderCount INT,          --记录总数 0:会返回总记录  
    748. @PageSize INT,               --每页输出的记录数  
    749. @PageIndex INT,              --当前页数  
    750. @TotalCount INT OUTPUT,      --记返回总记录  
    751. @TotalPageCount INT OUTPUT   --返回总页数  
    752.          */  
    753.         public static DataSet GetPageDataList2(string PrimaryKey, string FieldList, string TableName, string Where, string Order, int PageSize, int PageIndex)   
    754.         {   
    755.             string tableName = "viewPage";   
    756.             string storedProcName = "P_viewPage2";   
    757.             IDataParameter[] p = new IDataParameter[11];   
    758.             p[0] = new SqlParameter("TableName", TableName);   
    759.             p[1] = new SqlParameter("FieldList", FieldList);   
    760.             p[2] = new SqlParameter("PrimaryKey", PrimaryKey);   
    761.             p[3] = new SqlParameter("Where", Where);   
    762.             p[4] = new SqlParameter("Order", Order);   
    763.             p[5] = new SqlParameter("SortType", 3);   
    764.             p[6] = new SqlParameter("RecorderCount", 0);   
    765.             p[7] = new SqlParameter("PageSize", PageSize);   
    766.             p[8] = new SqlParameter("PageIndex", PageIndex);   
    767.             p[9] = new SqlParameter("TotalCount", 0);   
    768.             p[10] = new SqlParameter("TotalPageCount", 0);   
    769.   
    770.   
    771.             return RunProcedure(storedProcName, p, tableName);   
    772.         }   
    773.   
    774.         /// <summary>   
    775.         /// 构建 SqlCommand 对象(用来返回一个结果集,而不是一个整数值)   
    776.         /// </summary>   
    777.         /// <param name="connection">数据库连接</param>   
    778.         /// <param name="storedProcName">存储过程名</param>   
    779.         /// <param name="parameters">存储过程参数</param>   
    780.         /// <returns>SqlCommand</returns>   
    781.         private static SqlCommand BuildQueryCommand(SqlConnection connection, string storedProcName, IDataParameter[] parameters)   
    782.         {   
    783.             SqlCommand command = new SqlCommand(storedProcName, connection);   
    784.             command.CommandType = CommandType.StoredProcedure;   
    785.             foreach (SqlParameter parameter in parameters)   
    786.             {   
    787.                 if (parameter != null)   
    788.                 {   
    789.                     // 检查未分配值的输出参数,将其分配以DBNull.Value.   
    790.                     if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) &&   
    791.                         (parameter.Value == null))   
    792.                     {   
    793.                         parameter.Value = DBNull.Value;   
    794.                     }   
    795.                     command.Parameters.Add(parameter);   
    796.                 }   
    797.             }   
    798.   
    799.             return command;   
    800.         }   
    801.   
    802.         /// <summary>   
    803.         /// 执行存储过程,返回影响的行数         
    804.         /// </summary>   
    805.         /// <param name="storedProcName">存储过程名</param>   
    806.         /// <param name="parameters">存储过程参数</param>   
    807.         /// <param name="rowsAffected">影响的行数</param>   
    808.         /// <returns></returns>   
    809.         public static int RunProcedure(string storedProcName, IDataParameter[] parameters, out int rowsAffected)   
    810.         {   
    811.             using (SqlConnection connection = new SqlConnection(connectionString))   
    812.             {   
    813.                 int result;   
    814.                 connection.Open();   
    815.                 SqlCommand command = BuildIntCommand(connection, storedProcName, parameters);   
    816.                 rowsAffected = command.ExecuteNonQuery();   
    817.                 result = (int)command.Parameters["ReturnValue"].Value;   
    818.                 //Connection.Close();   
    819.                 return result;   
    820.             }   
    821.         }   
    822.   
    823.         /// <summary>   
    824.         /// 创建 SqlCommand 对象实例(用来返回一个整数值)      
    825.         /// </summary>   
    826.         /// <param name="storedProcName">存储过程名</param>   
    827.         /// <param name="parameters">存储过程参数</param>   
    828.         /// <returns>SqlCommand 对象实例</returns>   
    829.         private static SqlCommand BuildIntCommand(SqlConnection connection, string storedProcName, IDataParameter[] parameters)   
    830.         {   
    831.             SqlCommand command = BuildQueryCommand(connection, storedProcName, parameters);   
    832.             command.Parameters.Add(new SqlParameter("ReturnValue",   
    833.                 SqlDbType.Int, 4, ParameterDirection.ReturnValue,   
    834.                 false, 0, 0, string.Empty, DataRowVersion.Default, null));   
    835.             return command;   
    836.         }  
    837.         #endregion  
    838.  
    839.         #region SQL语句式分页   
    840.         /// <summary>      
    841.         /// 智能返回SQL语句      
    842.         /// </summary>      
    843.         /// <param name="primaryKey">主键(不能为空)</param>      
    844.         /// <param name="queryFields">提取字段(不能为空)</param>      
    845.         /// <param name="tableName">表(理论上允许多表)</param>      
    846.         /// <param name="condition">条件(可以空)</param>      
    847.         /// <param name="OrderBy">排序,格式:字段名+""+ASC(可以空)</param>      
    848.         /// <param name="pageSize">分页数(不能为空)</param>      
    849.         /// <param name="pageIndex">当前页,起始为:1(不能为空)</param>      
    850.         /// <returns></returns>      
    851.   
    852.         public static DataSet GetPageDataListSQL(string primaryKey, string queryFields, string tableName, string condition, string orderBy, int pageSize, int pageIndex)   
    853.         {   
    854.             string strTmp = ""//---strTmp用于返回的SQL语句      
    855.             string SqlSelect = "", SqlPrimaryKeySelect = "", strOrderBy = "", strWhere = " where 1=1 ", strTop = "";   
    856.             //0:分页数量      
    857.             //1:提取字段      
    858.             //2:表      
    859.             //3:条件      
    860.             //4:主键不存在的记录      
    861.             //5:排序      
    862.             SqlSelect = " select top {0} {1} from {2} {3} {4} {5}";   
    863.             //0:主键      
    864.             //1:TOP数量,为分页数*(排序号-1)      
    865.             //2:表      
    866.             //3:条件      
    867.             //4:排序      
    868.             SqlPrimaryKeySelect = " and {0} not in (select {1} {0} from {2} {3} {4}) ";   
    869.   
    870.             if (orderBy != "")   
    871.                 strOrderBy = " order by " + orderBy;   
    872.             if (condition != "")   
    873.                 strWhere += " and " + condition;   
    874.             int pageindexsize = (pageIndex - 1) * pageSize;   
    875.             if (pageindexsize > 0)   
    876.             {   
    877.                 strTop = " top " + pageindexsize.ToString();   
    878.   
    879.                 SqlPrimaryKeySelect = String.Format(SqlPrimaryKeySelect, primaryKey, strTop, tableName, strWhere, strOrderBy);   
    880.   
    881.                 strTmp = String.Format(SqlSelect, pageSize.ToString(), queryFields, tableName, strWhere, SqlPrimaryKeySelect, strOrderBy);   
    882.   
    883.             }   
    884.             else  
    885.             {   
    886.                 strTmp = String.Format(SqlSelect, pageSize.ToString(), queryFields, tableName, strWhere, "", strOrderBy);   
    887.   
    888.             }   
    889.             return Query(strTmp);   
    890.         }     
    891.         #endregion  
    892.         #region 获取安全的SQL字符串   
    893.         /// <summary>   
    894.         /// 获取安全的SQL字符串   
    895.         /// </summary>   
    896.         /// <param name="sql"></param>   
    897.         /// <returns></returns>   
    898.         public static string GetSafeSQLString(string sql)   
    899.         {   
    900.             sql = sql.Replace(","",");   
    901.             sql = sql.Replace(".""。");   
    902.             sql = sql.Replace("(""(");   
    903.             sql = sql.Replace(")"")");   
    904.             sql = sql.Replace(">"">");   
    905.             sql = sql.Replace("<""<");   
    906.             sql = sql.Replace("-""-");   
    907.             sql = sql.Replace("+""+");   
    908.             sql = sql.Replace("=""=");   
    909.             sql = sql.Replace("?""?");   
    910.             sql = sql.Replace("*""*");   
    911.             sql = sql.Replace("|""|");   
    912.             sql = sql.Replace("&""&");   
    913.             return sql;   
    914.         }  
    915.         #endregion   
    916.     }   
    917.   
    918. }  

    @数据列表插入操作:

    c# 代码
     
    1. public void GetDateList()   
    2. {   
    3.     string table = "Users";   
    4.     string where = " 1=1 ";   
    5.   
    6.     AspNetPager1.RecordCount = DbHelperSQL.GetDataRecordCount("UserID", table, where);//统计行数   
    7.   
    8.   
    9.     DataTable dt = DbHelperSQL.GetPageDataList("UserID""*", table, where, "id desc", AspNetPager1.PageSize, AspNetPager1.CurrentPageIndex).Tables[0];//这里面的ASPNETPAGER是一个分页控件,网上很多很通用的   
    10.     this.GVList.DataSource = dt;   
    11.     this.GVList.DataBind();   
    12. }   

    @插入操作【我这里用到的是存储过程】

    c# 代码
     
    1. /// <summary>   
    2. /// 用途:向表TB_Article新增记录   
    3. /// 时间:2007/9/17   
    4. /// 创建人:陈峰   
    5. /// </summary>   
    6. /// <param name="AttributeID">属性ID</param>   
    7. /// <param name="TeamBuyInfoID">团购活动ID</param>   
    8. /// <param name="Title">标题</param>   
    9. /// <param name="Content">内容</param>   
    10. /// <param name="MemberName">发表人</param>   
    11. /// <param name="MemberID">发表者ID</param>   
    12.   
    13. /// <returns></returns>   
    14. public string InsertTB_Article(int AttributeID, string Links, int TeamBuyInfoID, string Title, string Content, string MemberName, int MemberID)   
    15. {   
    16.     IDataParameter[] p = new IDataParameter[7];   
    17.     p[0] = new SqlParameter("AttributeID", AttributeID);   
    18.     p[1] = new SqlParameter("Links", Links);   
    19.     p[2] = new SqlParameter("TeamBuyInfoID", TeamBuyInfoID);   
    20.     p[3] = new SqlParameter("Title", Title);   
    21.     p[4] = new SqlParameter("Content", Content);   
    22.     p[5] = new SqlParameter("MemberName", MemberName);   
    23.     p[6] = new SqlParameter("MemberID", MemberID);   
    24.   
    25.   
    26.     return DbHelperSQL.RunProcedureState("Proc_Add_TB_Article", p);   
    27. }   

    另外我里面有3个分页程序,2个是需要用到存储过程,另一个是由ACCESS演化而来,效率上不比存储过程差

    sql 代码
     
    1.   
    2. CREATE Procedure P_viewPage   
    3.  /* Param List */   
    4. @TableNames VARCHAR(200),    --表名,可以是多个表,但不能用别名   
    5. @PrimaryKey VARCHAR(100),    --主键,可以为空,但@Order为空时该值不能为空   
    6. @Fields    VARCHAR(200),        --要取出的字段,可以是多个表的字段,可以为空,为空表示select *   
    7. @PageSize INT,            --每页记录数   
    8. @CurrentPage INT,        --当前页,0表示第1页   
    9. @Filter VARCHAR(200) = '',    --条件,可以为空,不用填 where   
    10. @Group VARCHAR(200) = '',    --分组依据,可以为空,不用填 group by   
    11. @Order VARCHAR(200) = ''    --排序,可以为空,为空默认按主键升序排列,不用填 order by   
    12. AS  
    13. BEGIN  
    14.     DECLARE @SortColumn VARCHAR(200)   
    15.     DECLARE @Operator CHAR(2)   
    16.     DECLARE @SortTable VARCHAR(200)   
    17.     DECLARE @SortName VARCHAR(200)   
    18.     IF @Fields = ''  
    19.         SET @Fields = '*'   
    20.     IF @Filter = ''  
    21.         SET @Filter = 'WHERE 1=1'   
    22.     ELSE  
    23.         SET @Filter = 'WHERE ' +  @Filter   
    24.     IF @Group <>''  
    25.         SET @Group = 'GROUP BY ' + @Group  
    26.   
    27.     IF @Order <> ''  
    28.     BEGIN  
    29.         DECLARE @pos1 INT, @pos2 INT  
    30.         SET @Order = REPLACE(REPLACE(@Order, ' asc', ' ASC'), ' desc', ' DESC')   
    31.         IF CHARINDEX(' DESC', @Order) > 0   
    32.             IF CHARINDEX(' ASC', @Order) > 0   
    33.             BEGIN  
    34.                 IF CHARINDEX(' DESC', @Order) < CHARINDEX(' ASC', @Order)   
    35.                     SET @Operator = '<='   
    36.                 ELSE  
    37.                     SET @Operator = '>='   
    38.             END  
    39.             ELSE  
    40.                 SET @Operator = '<='   
    41.         ELSE  
    42.             SET @Operator = '>='   
    43.         SET @SortColumn = REPLACE(REPLACE(REPLACE(@Order, ' ASC', ''), ' DESC', ''), ' ', '')   
    44.         SET @pos1 = CHARINDEX(',', @SortColumn)   
    45.         IF @pos1 > 0   
    46.             SET @SortColumn = SUBSTRING(@SortColumn, 1, @pos1-1)   
    47.         SET @pos2 = CHARINDEX('.', @SortColumn)   
    48.         IF @pos2 > 0   
    49.         BEGIN  
    50.             SET @SortTable = SUBSTRING(@SortColumn, 1, @pos2-1)   
    51.             IF @pos1 > 0    
    52.                 SET @SortName = SUBSTRING(@SortColumn, @pos2+1, @pos1-@pos2-1)   
    53.             ELSE  
    54.                 SET @SortName = SUBSTRING(@SortColumn, @pos2+1, LEN(@SortColumn)-@pos2)   
    55.         END  
    56.         ELSE  
    57.         BEGIN  
    58.             SET @SortTable = @TableNames   
    59.             SET @SortName = @SortColumn   
    60.         END  
    61.     END  
    62.     ELSE  
    63.     BEGIN  
    64.         SET @SortColumn = @PrimaryKey   
    65.         SET @SortTable = @TableNames   
    66.         SET @SortName = @SortColumn   
    67.         SET @Order = @SortColumn   
    68.         SET @Operator = '>='   
    69.     END  
    70.   
    71.     DECLARE @type varchar(50)   
    72.     DECLARE @prec int  
    73.     SELECT @type=t.name, @prec=c.prec   
    74.     FROM sysobjects o    
    75.     JOIN syscolumns c on o.id=c.id   
    76.     JOIN systypes t on c.xusertype=t.xusertype   
    77.     WHERE o.name = @SortTable AND c.name = @SortName   
    78.     IF CHARINDEX('char', @type) > 0   
    79.     SET @type = @type + '(' + CAST(@prec AS varchar) + ')'   
    80.   
    81.     DECLARE @TopRows INT  
    82.     SET @TopRows = @PageSize * @CurrentPage +1   
    83.     print @TopRows   
    84.     print @Operator   
    85.     EXEC('   
    86.         DECLARE @SortColumnBegin ' + @type + '   
    87.         SET ROWCOUNT ' + @TopRows + '   
    88.         SELECT @SortColumnBegin=' + @SortColumn + ' FROM  ' + @TableNames + ' ' + @Filter + ' ' + @Group + ' ORDER BY ' + @Order + '   
    89.         SET ROWCOUNT ' + @PageSize + '   
    90.         SELECT ' + @Fields + ' FROM  ' + @TableNames + ' ' + @Filter  + ' AND ' + @SortColumn + '' + @Operator + '@SortColumnBegin ' + @Group + ' ORDER BY ' + @Order + '       
    91.     ')       
    92. END  
    93. GO   
    94. SET QUOTED_IDENTIFIER OFF    
    95. GO   
    96. SET ANSI_NULLS ON    
    97. GO   
    98.   
    99. SET QUOTED_IDENTIFIER ON    
    100. GO   
    101. SET ANSI_NULLS OFF    
    102. GO   
    103.   
    104. CREATE PROC P_viewPage2   
    105. /*   
    106. nzperfect [no_mIss] 高效通用分页存储过程(双向检索) 2007.5.7  QQ:34813284   
    107. 敬告:适用于单一主键或存在唯一值列的表或视图   
    108. ps:Sql语句为8000字节,调用时请注意传入参数及sql总长度不要超过指定范围   
    109. */   
    110. @TableName VARCHAR(200),     --表名   
    111. @FieldList VARCHAR(2000),    --显示列名,如果是全部字段则为*   
    112. @PrimaryKey VARCHAR(100),    --单一主键或唯一值键   
    113. @Where VARCHAR(2000),        --查询条件 不含'where'字符,如id>10 and len(userid)>9   
    114. @Order VARCHAR(1000),        --排序 不含'order by'字符,如id asc,userid desc,必须指定asc或desc   
    115. --注意当@SortType=3时生效,记住一定要在最后加上主键,否则会让你比较郁闷   
    116. @SortType INT,               --排序规则 1:正序asc 2:倒序desc 3:多列排序方法   
    117. @RecorderCount INT,          --记录总数 0:会返回总记录   
    118. @PageSize INT,               --每页输出的记录数   
    119. @PageIndex INT,              --当前页数   
    120. @TotalCount INT OUTPUT,      --记返回总记录   
    121. @TotalPageCount INT OUTPUT   --返回总页数   
    122. AS  
    123. SET NOCOUNT ON  
    124. IF ISNULL(@TotalCount,'') = '' SET @TotalCount = 0   
    125. SET @Order = RTRIM(LTRIM(@Order))   
    126. SET @PrimaryKey = RTRIM(LTRIM(@PrimaryKey))   
    127. SET @FieldList = REPLACE(RTRIM(LTRIM(@FieldList)),' ','')   
    128. WHILE CHARINDEX(', ',@Order) > 0 OR CHARINDEX(' ,',@Order) > 0   
    129. BEGIN  
    130. SET @Order = REPLACE(@Order,', ',',')   
    131. SET @Order = REPLACE(@Order,' ,',',')   
    132. END  
    133. IF ISNULL(@TableName,'') = '' OR ISNULL(@FieldList,'') = ''  
    134. OR ISNULL(@PrimaryKey,'') = ''  
    135. OR @SortType < 1 OR @SortType >3   
    136. OR @RecorderCount  < 0 OR @PageSize < 0 OR @PageIndex < 0   
    137. BEGIN  
    138. PRINT('ERR_00')   
    139. RETURN  
    140. END  
    141. IF @SortType = 3   
    142. BEGIN  
    143. IF (UPPER(RIGHT(@Order,4))!=' ASCAND UPPER(RIGHT(@Order,5))!=' DESC')   
    144. BEGIN PRINT('ERR_02') RETURN END  
    145. END  
    146. DECLARE @new_where1 VARCHAR(1000)   
    147. DECLARE @new_where2 VARCHAR(1000)   
    148. DECLARE @new_order1 VARCHAR(1000)   
    149. DECLARE @new_order2 VARCHAR(1000)   
    150. DECLARE @new_order3 VARCHAR(1000)   
    151. DECLARE @Sql VARCHAR(8000)   
    152. DECLARE @SqlCount NVARCHAR(4000)   
    153. IF ISNULL(@where,'') = ''  
    154. BEGIN  
    155. SET @new_where1 = ' '   
    156. SET @new_where2 = ' WHERE  '   
    157. END  
    158. ELSE  
    159. BEGIN  
    160. SET @new_where1 = ' WHERE ' + @where  
    161. SET @new_where2 = ' WHERE ' + @where + ' AND '   
    162. END  
    163. IF ISNULL(@order,'') = '' OR @SortType = 1  OR @SortType = 2   
    164. BEGIN  
    165. IF @SortType = 1   
    166. BEGIN  
    167. SET @new_order1 = ' ORDER BY ' + @PrimaryKey + ' ASC'   
    168. SET @new_order2 = ' ORDER BY ' + @PrimaryKey + ' DESC'   
    169. END  
    170. IF @SortType = 2   
    171. BEGIN  
    172. SET @new_order1 = ' ORDER BY ' + @PrimaryKey + ' DESC'   
    173. SET @new_order2 = ' ORDER BY ' + @PrimaryKey + ' ASC'   
    174. END  
    175. END  
    176. ELSE  
    177. BEGIN  
    178. SET @new_order1 = ' ORDER BY ' + @Order  
    179. END  
    180. IF @SortType = 3 AND  CHARINDEX(','+@PrimaryKey+' ',','+@Order)>0   
    181. BEGIN  
    182. SET @new_order1 = ' ORDER BY ' + @Order  
    183. SET @new_order2 = @Order + ','   
    184. SET @new_order2 = REPLACE(REPLACE(@new_order2,'ASC,','{ASC},'),'DESC,','{DESC},')   
    185. SET @new_order2 = REPLACE(REPLACE(@new_order2,'{ASC},','DESC,'),'{DESC},','ASC,')   
    186. SET @new_order2 = ' ORDER BY ' + SUBSTRING(@new_order2,1,LEN(@new_order2)-1)   
    187. IF @FieldList <> '*'   
    188. BEGIN  
    189. SET @new_order3 = REPLACE(REPLACE(@Order + ',','ASC,',','),'DESC,',',')   
    190. SET @FieldList = ',' + @FieldList   
    191. WHILE CHARINDEX(',',@new_order3)>0   
    192. BEGIN  
    193. IF CHARINDEX(SUBSTRING(','+@new_order3,1,CHARINDEX(',',@new_order3)),','+@FieldList+',')>0   
    194. BEGIN  
    195. SET @FieldList =   
    196. @FieldList + ',' + SUBSTRING(@new_order3,1,CHARINDEX(',',@new_order3))   
    197. END  
    198. SET @new_order3 =   
    199. SUBSTRING(@new_order3,CHARINDEX(',',@new_order3)+1,LEN(@new_order3))   
    200. END  
    201. SET @FieldList = SUBSTRING(@FieldList,2,LEN(@FieldList))   
    202. END  
    203. END  
    204. SET @SqlCount = 'SELECT @TotalCount=COUNT(*),@TotalPageCount=CEILING((COUNT(*)+0.0)/'   
    205. CAST(@PageSize AS VARCHAR)+') FROM ' + @TableName + @new_where1   
    206.   
    207. BEGIN  
    208. EXEC SP_EXECUTESQL @SqlCount,N'@TotalCount INT OUTPUT,@TotalPageCount INT OUTPUT',   
    209. @TotalCount OUTPUT,@TotalPageCount OUTPUT  
    210. END  
    211.   
    212. IF @PageIndex > CEILING((@TotalCount+0.0)/@PageSize)   
    213. BEGIN  
    214. SET @PageIndex =  CEILING((@TotalCount+0.0)/@PageSize)   
    215. END  
    216. IF @PageIndex = 1 OR @PageIndex >= CEILING((@TotalCount+0.0)/@PageSize)   
    217. BEGIN  
    218. IF @PageIndex = 1 --返回第一页数据   
    219. BEGIN  
    220. SET @Sql = 'SELECT TOP ' + STR(@PageSize) + ' ' + @FieldList + ' FROM '   
    221. + @TableName + @new_where1 + @new_order1   
    222. END  
    223. IF @PageIndex >= CEILING((@TotalCount+0.0)/@PageSize)  --返回最后一页数据   
    224. BEGIN  
    225. SET @Sql = 'SELECT TOP ' + STR(@PageSize) + ' ' + @FieldList + ' FROM ('   
    226. + 'SELECT TOP ' + STR(ABS(@PageSize*@PageIndex-@TotalCount-@PageSize))   
    227. + ' ' + @FieldList + ' FROM '   
    228. + @TableName + @new_where1 + @new_order2 + ' ) AS TMP '   
    229. + @new_order1   
    230. END  
    231. END  
    232. ELSE  
    233. BEGIN  
    234. IF @SortType = 1  --仅主键正序排序   
    235. BEGIN  
    236. IF @PageIndex <= CEILING((@TotalCount+0.0)/@PageSize)/2  --正向检索   
    237. BEGIN  
    238. SET @Sql = 'SELECT TOP ' + STR(@PageSize) + ' ' + @FieldList + ' FROM '   
    239. + @TableName + @new_where2 + @PrimaryKey + ' > '   
    240. + '(SELECT MAX(' + @PrimaryKey + ') FROM (SELECT TOP '   
    241. + STR(@PageSize*(@PageIndex-1)) + ' ' + @PrimaryKey   
    242. + ' FROM ' + @TableName   
    243. + @new_where1 + @new_order1 +' ) AS TMP) '+ @new_order1   
    244. END  
    245. ELSE  --反向检索   
    246. BEGIN  
    247. SET @Sql = 'SELECT TOP ' + STR(@PageSize) + ' ' + @FieldList + ' FROM ('   
    248. + 'SELECT TOP ' + STR(@PageSize) + ' '   
    249. + @FieldList + ' FROM '   
    250. + @TableName + @new_where2 + @PrimaryKey + ' < '   
    251. + '(SELECT MIN(' + @PrimaryKey + ') FROM (SELECT TOP '   
    252. + STR(@TotalCount-@PageSize*@PageIndex) + ' ' + @PrimaryKey   
    253. + ' FROM ' + @TableName   
    254. + @new_where1 + @new_order2 +' ) AS TMP) '+ @new_order2   
    255. + ' ) AS TMP ' + @new_order1   
    256. END  
    257. END  
    258. IF @SortType = 2  --仅主键反序排序   
    259. BEGIN  
    260. IF @PageIndex <= CEILING((@TotalCount+0.0)/@PageSize)/2  --正向检索   
    261. BEGIN  
    262. SET @Sql = 'SELECT TOP ' + STR(@PageSize) + ' ' + @FieldList + ' FROM '   
    263. + @TableName + @new_where2 + @PrimaryKey + ' < '   
    264. + '(SELECT MIN(' + @PrimaryKey + ') FROM (SELECT TOP '   
    265. + STR(@PageSize*(@PageIndex-1)) + ' ' + @PrimaryKey   
    266. +' FROM '+ @TableName   
    267. + @new_where1 + @new_order1 + ') AS TMP) '+ @new_order1   
    268. END  
    269. ELSE  --反向检索   
    270. BEGIN  
    271. SET @Sql = 'SELECT TOP ' + STR(@PageSize) + ' ' + @FieldList + ' FROM ('   
    272. + 'SELECT TOP ' + STR(@PageSize) + ' '   
    273. + @FieldList + ' FROM '   
    274. + @TableName + @new_where2 + @PrimaryKey + ' > '   
    275. + '(SELECT MAX(' + @PrimaryKey + ') FROM (SELECT TOP '   
    276. + STR(@TotalCount-@PageSize*@PageIndex) + ' ' + @PrimaryKey   
    277. + ' FROM ' + @TableName   
    278. + @new_where1 + @new_order2 +' ) AS TMP) '+ @new_order2   
    279. + ' ) AS TMP ' + @new_order1   
    280. END  
    281. END  
    282. IF @SortType = 3  --多列排序,必须包含主键,且放置最后,否则不处理   
    283. BEGIN  
    284. IF CHARINDEX(',' + @PrimaryKey + ' ',',' + @Order) = 0   
    285. BEGIN PRINT('ERR_02') RETURN END  
    286. IF @PageIndex <= CEILING((@TotalCount+0.0)/@PageSize)/2  --正向检索   
    287. BEGIN  
    288. SET @Sql = 'SELECT TOP ' + STR(@PageSize) + ' ' + @FieldList + ' FROM ( '   
    289. + 'SELECT TOP ' + STR(@PageSize) + ' ' + @FieldList + ' FROM ( '   
    290. + ' SELECT TOP ' + STR(@PageSize*@PageIndex) + ' ' + @FieldList   
    291. + ' FROM ' + @TableName + @new_where1 + @new_order1 + ' ) AS TMP '   
    292. + @new_order2 + ' ) AS TMP ' + @new_order1   
    293. END  
    294. ELSE  --反向检索   
    295. BEGIN  
    296. SET @Sql = 'SELECT TOP ' + STR(@PageSize) + ' ' + @FieldList + ' FROM ( '   
    297. + 'SELECT TOP ' + STR(@PageSize) + ' ' + @FieldList + ' FROM ( '   
    298. + ' SELECT TOP ' + STR(@TotalCount-@PageSize *@PageIndex+@PageSize) + ' ' + @FieldList   
    299. + ' FROM ' + @TableName + @new_where1 + @new_order2 + ' ) AS TMP '   
    300. + @new_order1 + ' ) AS TMP ' + @new_order1   
    301. END  
    302. END  
    303. END  
    304. EXEC(@Sql)   
    305. GO   
    306. SET QUOTED_IDENTIFIER OFF    
    307. GO   
    308. SET ANSI_NULLS ON    
  • 相关阅读:
    Hsl PLC
    .NET平台常用框架整理
    SSH全注解实例详解
    word2vec (CBOW、分层softmax、负采样)
    pandas dataframe 一行变多行 (query pv统计term pv)
    python 按二维数组的某行或列排序 (numpy lexsort)
    基于决策树的分类算法
    【linux】 mail/mutt 发送邮件
    【python】含中文字符串截断
    【python】 判断纯ascii串
  • 原文地址:https://www.cnblogs.com/liufei88866/p/1511605.html
Copyright © 2020-2023  润新知