sqlserver创建存储过程、函数、
--有輸入?yún)?shù)的存儲過程--
create proc GetComment
(@commentid int)
as
select * from Comment where CommentID=@commentid
C# 調(diào)用有輸入?yún)?shù)的存儲過程
SqlConnection conn=new SqlConnection("Server=.;Database=MyDB;uid=sa;pwd=123456");
SqlCommand cmd=new SqlCommand();
cmd.Connection=conn;
cmd.CommandType=CommandType.StoredProcedure;
cmd.CommandText="GetComment";
cmd.Parameters.Clear();
cmd.Parameters.Add("@commentid",SqlDbType.Int).Value=1;
DataTable dt=new DataTable();
SqlDataAdapter da=new SqlDataAdapter(cmd);
da.Fill(dt);
GridView1.DataSource=dt;
GridView1.DataBind();
--有輸入與輸出參數(shù)的存儲過程--
create proc GetCommentCount
@newsid int,
@count int output
as
select @count=count(*) from Comment where NewsID=@newsid
?
SqlConnection conn=new SqlConnection("Server=.;DataBase=MyDB;uid=sa;pwd=123456");
SqlCommand cmd=new SqlCommand();
conn.Open();
cmd.Connection=conn;
cmd.CommandType=CommandType.StoredProcedure;
cmd.CommandText="GetCommentCount";
cmd.Parameters.Clear();
?
cmd.Parameters.Add("@newsid",SqlDbType.Int).Value=2;
SqlParameter sp=new SqlParameter();
sp.ParameterName="@count";
sp.SqlDbType=SqlDbType.Int;
sp.Direction=ParameterDirection.Output;
cmd.Parameters.Add(sp);
Response.Write(sp.Value.ToString());
--返回單個值的函數(shù)--
create function MyFunction
(@newsid int)
returns int
as
begin
declare @count int
select @count=count(*) from Comment where NewsID=@newsid
return @count
end
SqlConnection conn=new SqlConnection("Server=.;Database=MyDB;uid=sa;pwd=123456");
SqlCommand cmd=new SqlCommand();
conn.Open();
cmd.Connection=conn;
cmd.CommandText="MyFunction";
cmd.CommandType=CommandType.StoredProcedure;? -----這兒要設(shè)置為存儲過程
cmd.Parameters.Add("@newsid",SqlDbType.Int).Value=2;
SqlParameter sp=new SqlParameter();
sp.ParameterName="@count";
sp.SqlDbType=SqlDbType.Int;
sp.Direction=ParameterDirection.ReturnValue;
cmd.Parameters.Add(sp);
cmd.ExecuteNonQuery();
Response.Write(sp.Value.ToString());
--調(diào)用方法--
declare @count int
exec @count=MyFunction 2
print @count
?
--返回值為表的函數(shù)--
Create function GetFunctionTable
(@newsid int)
returns table
as
return
(select * from Comment where NewsID=@newsid)
?
--返回值為表的函數(shù)的調(diào)用--
select * from GetFunctionTable(2)
SqlConnection conn=new SqlConnection("Server=.;Database=MyDB;uid=sa;pwd=123456");
SqlCommand cmd=new SqlCommand();
conn.Open();
cmd.Connection=conn;
cmd.CommandType=CommandType.Text;//注意這兒設(shè)置為文本
cmd.CommandText="Select * from GetFunctionTable(@newsid)";
SqlDataReader dr=cmd.ExecuteReader();
DataTable dt=new DataTable();
dt.Load(dt);
GridView1.DataSource=dt;
GridView1.DataBind();
?
?
轉(zhuǎn)載于:https://blog.51cto.com/1906754/502000
總結(jié)
以上是生活随笔為你收集整理的sqlserver创建存储过程、函数、的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 21、深入浅出MFC学习笔记,Appli
- 下一篇: NET中的异步编程(二)- 传统的异步编