SQL SERVER中函數以及函數的調用ide
一、建立有返回值的函數函數
函數:get
CREATE Function GetCount(@typeid int)
returns int
as
begin
declare @result int
select @result=sum(ID) from books where TypeID=@typeid
if (@result is null)
set @result=0
return @result
endcmd
調用示例:it
SqlConnection conn = new SqlConnection("Server=.\\SQLEXPRESS;Initial Catalog=Test;Integrated Security=true");
conn.Open();io
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "GetCount";
SqlParameter sp = new SqlParameter("@typeid", SqlDbType.Int, 2);
sp.Direction = ParameterDirection.Input;
sp.Value = 1;
cmd.Parameters.Add(sp);
sp = new SqlParameter("@returnvalue", SqlDbType.Int, 4);
sp.Direction = ParameterDirection.ReturnValue;
cmd.Parameters.Add(sp);
cmd.ExecuteNonQuery();
Response.Write(cmd.Parameters["@returnvalue"].Value.ToString());table
二、建立返回表的函數function
函數:class
Create function GetTable(@typeid int)
returns table
as
return(select * from books where TypeID=@typeid)select
調用示例:
SqlConnection conn = new SqlConnection("Server=.\\SQLEXPRESS;Initial Catalog=Test;Integrated Security=true");
conn.Open();
SqlCommand cmd = new SqlCommand(); cmd.Connection = conn; cmd.CommandType = CommandType.Text ; cmd.CommandText = "select * from GetTable(@typeid)";//表值函數的調用 SqlParameter sp = new SqlParameter("@typeid", SqlDbType.Int, 2); sp.Direction = ParameterDirection.Input; sp.Value = 1; cmd.Parameters.Add(sp); SqlDataAdapter da = new SqlDataAdapter(cmd); DataTable dt = new DataTable(); da.Fill(dt); GridView1.DataSource = dt; GridView1.DataBind();