今天做项目,发现用存储过程比较实用。
当字段动态拼接时:
--1. 使用 EXEC 实现的动态参数存储过程 CREATE PROC p_test @para1 varchar(10)=null, @para2 varchar(10)=null, @para3 varchar(10)=null, @para4 varchar(10)=null AS SET NOCOUNT ON DECLARE @sql varchar(8000) SET @sql='SELECT * FROM tbname WHERE 1=1' IF @para1 IS NOT NULL SET @sql=@sql+' AND col1='''+@para1+'''' IF @para2 IS NOT NULL SET @sql=@sql+' AND col2='''+@para2+'''' IF @para3 IS NOT NULL SET @sql=@sql+' AND col3='''+@para3+'''' IF @para4 IS NOT NULL SET @sql=@sql+' AND col4='''+@para4+'''' EXEC(@sql) GO /*======================================================*/ --2. 使用 sp_executesql 实现的动态参数存储过程 CREATE PROC p_test @para1 varchar(10)=null, @para2 datetime=null, @para3 varchar(10)=null, @para4 int=null AS SET NOCOUNT ON DECLARE @sql nvarchar(4000) SET @sql='SELECT * FROM tbname WHERE 1=1' +CASE WHEN @para1 IS NULL THEN '' ELSE ' AND col1=@para1' END +CASE WHEN @para2 IS NULL THEN '' ELSE ' AND col2=@para2' END +CASE WHEN @para3 IS NULL THEN '' ELSE ' AND col3=@para3' END +CASE WHEN @para4 IS NULL THEN '' ELSE ' AND col4=@para4' END EXEC sp_executesql @sql,N' @para1 varchar(10)=null, @para2 datetime=null, @para3 varchar(10)=null, @para4 int=null ',@para1,@para2,@para3,@para4 GO /*======================================================*/ --3. 不使用动态 Transact-SQL 语句实现的动态参数存储过程 CREATE PROC p_test @para1 varchar(10)=null, @para2 datetime=null, @para3 varchar(10)=null, @para4 int=null AS SET NOCOUNT ON SELECT * FROM tbname WHERE (@para1 IS NULL OR col1=@para1) AND (@para2 IS NULL OR col2=@para2) AND (@para3 IS NULL OR col3=@para3) AND (@para4 IS NULL OR col4=@para4)
然后查找了一下存储过程,参照如下文章:
http://www.cnblogs.com/SkySoot/archive/2012/02/10/2345185.html
配置 App.config (注: 本文使用 Northwind 数据库为例)
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="NorthwindConnectionString" connectionString="Data Source=.;Initial Catalog=Northwind;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
获取连接字符串
string ConStr = ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString;
1. 返回单一记录集的存储过程
SqlConnection conn = new SqlConnection(ConStr); SqlCommand cmd = new SqlCommand(); cmd.Connection = conn; cmd.CommandText = "Categoriestest1"; // 指定执行语句为存储过程 cmd.CommandType = CommandType.StoredProcedure; SqlDataAdapter dp = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); dp.Fill(ds); GridView1.DataSource = ds; GridView1.DataBind();存储过程Categoriestest1
CREATE PROCEDURE Categoriestest1 AS select * from Categories GO2. 没有输入输出的存储过程
SqlConnection conn = new SqlConnection(ConStr); SqlCommand cmd = new SqlCommand(); cmd.Connection = conn ; cmd.CommandText = "Categoriestest2"; cmd.CommandType = CommandType.StoredProcedure; conn.Open(); Label1.Text = cmd.ExecuteNonQuery().ToString(); conn.Close();
CREATE PROCEDURE Categoriestest2 AS insert into dbo.Categories (CategoryName,[Description],[Picture]) values ('test1','test1',null) GO3. 有返回值的存储过程
SqlConnection conn = new SqlConnection(ConStr); SqlCommand cmd = new SqlCommand(); cmd.Connection = conn; cmd.CommandText = "Categoriestest3"; cmd.CommandType = CommandType.StoredProcedure; // 创建参数 IDataParameter[] parameters = { new SqlParameter("rval", SqlDbType.Int,4) }; // 将参数类型设置为 返回值类型 parameters[0].Direction = ParameterDirection.ReturnValue; // 添加参数 cmd.Parameters.Add(parameters[0]); conn.Open(); // 执行存储过程并返回影响的行数 Label1.Text = cmd.ExecuteNonQuery().ToString(); conn.Close(); // 显示影响的行数和返回值 Label1.Text += "-" + parameters[0].Value.ToString();存储过程Categoriestest3
CREATE PROCEDURE Categoriestest3 AS insert into dbo.Categories (CategoryName,[Description],[Picture]) values ('test1','test1',null) return @@rowcount GO4. 有输入参数和输出参数的存储过程
SqlConnection conn = new SqlConnection(ConStr); SqlCommand cmd = new SqlCommand(); cmd.Connection = conn; cmd.CommandText = "Categoriestest4"; cmd.CommandType = CommandType.StoredProcedure; // 创建参数 IDataParameter[] parameters = { new SqlParameter("@Id", SqlDbType.Int,4) , new SqlParameter("@CategoryName", SqlDbType.NVarChar,15) , }; // 设置参数类型 parameters[0].Direction = ParameterDirection.Output; // 设置为输出参数 parameters[1].Value = "testCategoryName"; // 添加参数 cmd.Parameters.Add(parameters[0]); cmd.Parameters.Add(parameters[1]); conn.Open(); // 执行存储过程并返回影响的行数 Label1.Text = cmd.ExecuteNonQuery().ToString(); conn.Close(); // 显示影响的行数和输出参数 Label1.Text += "-" + parameters[0].Value.ToString();存储过程Categoriestest4
CREATE PROCEDURE Categoriestest4 @id int output, @CategoryName nvarchar(15) AS insert into dbo.Categories (CategoryName,[Description],[Picture]) values (@CategoryName,'test1',null) set @id = @@IDENTITY GO
SqlConnection conn = new SqlConnection(ConStr); SqlCommand cmd = new SqlCommand(); cmd.Connection = conn; cmd.CommandText = "Categoriestest5"; cmd.CommandType = CommandType.StoredProcedure; // 创建参数 IDataParameter[] parameters = { new SqlParameter("@Id", SqlDbType.Int,4) , new SqlParameter("@CategoryName", SqlDbType.NVarChar,15) , new SqlParameter("rval", SqlDbType.Int,4) }; // 设置参数类型 parameters[0].Direction = ParameterDirection.Output; // 设置为输出参数 parameters[1].Value = "testCategoryName"; // 给输入参数赋值 parameters[2].Direction = ParameterDirection.ReturnValue; // 设置为返回值 // 添加参数 cmd.Parameters.Add(parameters[0]); cmd.Parameters.Add(parameters[1]); cmd.Parameters.Add(parameters[2]); conn.Open(); // 执行存储过程并返回影响的行数 Label1.Text = cmd.ExecuteNonQuery().ToString(); conn.Close(); // 显示影响的行数,输出参数和返回值 Label1.Text += "-" + parameters[0].Value.ToString() + "-" + parameters[2].Value.ToString();存储过程Categoriestest5
CREATE PROCEDURE Categoriestest5 @id int output, @CategoryName nvarchar(15) AS insert into dbo.Categories (CategoryName,[Description],[Picture]) values (@CategoryName,'test1',null) set @id = @@IDENTITY return @@rowcount GO6. 同时返回参数和记录集的存储过程
SqlConnection conn = new SqlConnection(ConStr); SqlCommand cmd = new SqlCommand(); cmd.Connection = conn; cmd.CommandText = "Categoriestest6"; cmd.CommandType = CommandType.StoredProcedure; // 创建参数 IDataParameter[] parameters = { new SqlParameter("@Id", SqlDbType.Int,4) , new SqlParameter("@CategoryName", SqlDbType.NVarChar,15) , new SqlParameter("rval", SqlDbType.Int,4) // 返回值 }; // 设置参数类型 parameters[0].Direction = ParameterDirection.Output; // 设置为输出参数 parameters[1].Value = "testCategoryName"; // 给输入参数赋值 parameters[2].Direction = ParameterDirection.ReturnValue; // 设置为返回值 // 添加参数 cmd.Parameters.Add(parameters[0]); cmd.Parameters.Add(parameters[1]); cmd.Parameters.Add(parameters[2]); SqlDataAdapter dp = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); dp.Fill(ds); GridView1.DataSource = ds.Tables[0]; GridView1.DataBind(); Label1.Text = string.Empty; // 显示输出参数和返回值 Label1.Text += parameters[0].Value.ToString() + "-" + parameters[2].Value.ToString();存储过程Categoriestest6
CREATE PROCEDURE Categoriestest6 @id int output, @CategoryName nvarchar(15) AS insert into dbo.Categories (CategoryName,[Description],[Picture]) values (@CategoryName,'test1',null) set @id = @@IDENTITY select * from Categories return @@rowcount GO7. 返回多个记录集的存储过程
SqlConnection conn = new SqlConnection(ConStr); SqlCommand cmd = new SqlCommand(); cmd.Connection = conn; cmd.CommandText = "Categoriestest7"; cmd.CommandType = CommandType.StoredProcedure; SqlDataAdapter dp = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); dp.Fill(ds); GridView1.DataSource = ds.Tables[0]; GridView1.DataBind(); GridView2.DataSource = ds.Tables[1]; GridView2.DataBind();存储过程Categoriestest7
CREATE PROCEDURE Categoriestest7 AS select * from Categories select * from Categories GO