在SQL Server 2008的存储过程中使用 OUTPUT关键字

在本文中,将介绍如何在存储过程中使用 output 关键字。
首先创建一个表

create table login(uIdd varchar(15),uPwdd varchar(15))

插入数据

insert into login

select 'admin','admin'union all

select 'user','user'

创建存储过程:

create proc usp_select(@id varchar(15) output,@pwd varchar(15))

as

select * from login where jack@onitroad and jack@onitroad

执行存储过程

exec usp_select 'user','user'

现在在网页中编写以下源代码。

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="page1.aspx.cs" Inherits="page1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

<title></title>

</head>

<body>

<form id="form1" runat="server">

<div>

<table>

  <tr><td>click here to get username</td><td><asp:Button ID="btn1" Text="get user Id" runat="server" OnClick="btn1_Click" /></td></tr>

  <tr><td> </td><td><asp:Label ID="lbl1" runat="server"></asp:Label></td></tr>

</table>

</div>

</form>

</body>

</html>

现在在Web页面中写下以下源代码:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Data;

using System.Data.SqlClient;

public partial class page1 : System.Web.UI.Page

{

SqlConnection con = new SqlConnection("server=.;database=outputsp; user id=sa;pwd=wintellect");

SqlCommand cmd;

protected void Page_Load(object sender, EventArgs e)

{

  con.Open();

  Response.Write("ya");

  con.Close();

}

protected void btn1_Click(object sender, EventArgs e)

{

  string str="admin";

  cmd = new SqlCommand("usp_select", con);

  cmd.CommandType = CommandType.StoredProcedure;

  cmd.Parameters.AddWithValue("@id", str);

  cmd.Parameters.AddWithValue("@pwd", str);

  con.Open();

  cmd.ExecuteNonQuery();

  cmd.Parameters.Add("@id", SqlDbType.Char, 500);

  cmd.Parameters["@id"].Direction = ParameterDirection.Output;

  string userName = (string)cmd.Parameters["@id"].Value;

  lbl1.Text = userName;

}

}
日期:2020-06-02 22:18:12 来源:oir作者:oir