微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

sqlserver创建存储过程、函数、

--有输入参数的存储过程--

create proc GetComment

(@commentid int)

as

select * from Comment where CommentID=@commentid

C# 调用有输入参数的存储过程

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();

--有输入与输出参数的存储过程--

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());

--返回单个值的函数--

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;  -----这儿要设置为存储过程

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());

--调用方法--

declare @count int

exec @count=MyFunction 2

print @count

 

--返回值为表的函数--

Create function GetFunctionTable

(@newsid int)

returns table

as

return

(select * from Comment where NewsID=@newsid)

 

--返回值为表的函数调用--

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;//注意这儿设置为文本

cmd.CommandText="Select * from GetFunctionTable(@newsid)";

sqlDataReader dr=cmd.ExecuteReader();

DataTable dt=new DataTable();

dt.Load(dt);

GridView1.DataSource=dt;

GridView1.DataBind();

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐