SQL SERVER中函數以及函數的調用
1、創建有返回值的函數
函數:
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
end
調用示例:
SqlConnection conn = new SqlConnection("Server=.\\SQLEXPRESS;Initial Catalog=Test;Integrated Security=true");
conn.Open();
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());
2、創建返回表的函數
函數:
Create function GetTable(@typeid int)
returns table
as
return(select * from books where TypeID=@typeid)
調用示例:
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();