C calls the stored procedure in simple and complete instance code

  • 2020-05-07 19:32:04
  • OfStack

CREATE PROC P_TEST@Name VARCHAR(20),
@Rowcount INT OUTPUT
AS
BEGIN
SELECT * FROM T_Customer WHERE NAME=@Name
SET @Rowcount=@@ROWCOUNT
END
GO
----------------------------------------------------------------------------------------
-- the stored procedure is called as follows:
----------------------------------------------------------------------------------------
DECLARE @i INT
EXEC P_TEST 'A',@i OUTPUT
SELECT @i
Results -
/*
Name Address Tel
---------- ---------- --------------------
A Address Telphone

(the number of rows affected is 1)


-----------
1

(the number of rows affected is 1)
*/
----------------------------------------------------------------------------------------

- DotNet part (C #)
- WebConfig file:
----------------------------------------------------------------------------------------
......
< /system.web >

< ! Database connection string
-- >
< appSettings >
< add key="ConnectString" value="server=(local);User ID=sa;Password=;database=Test" / >
< /appSettings >

< /configuration >
----------------------------------------------------------------------------------------
--C# code :(two test controls are used,DataGrid1(to display the binding result set),Lable(to display the stored procedure return single value)

code
 
using System.Data.SqlClient; 
private void Page_Load(object sender, System.EventArgs e) 

{ //  Place the user code here to initialize the page  
String DBConnStr; DataSet MyDataSet=new DataSet(); 
System.Data.SqlClient.SqlDataAdapter DataAdapter=new System.Data.SqlClient.SqlDataAdapter(); 
DBConnStr=System.Configuration.ConfigurationSettings.AppSettings["ConnectString"]; 
System.Data.SqlClient.SqlConnection myConnection = new System.Data.SqlClient.SqlConnection(DBConnStr); 
if (myConnection.State!=ConnectionState.Open) 
{ myConnection.Open(); } 
System.Data.SqlClient.SqlCommand myCommand = new System.Data.SqlClient.SqlCommand("P_Test",myConnection); 
myCommand.CommandType=CommandType.StoredProcedure; // Add input query parameters and assign values  
myCommand.Parameters.Add("@Name",SqlDbType.VarChar); 
myCommand.Parameters["@Name"].Value ="A"; // Add output parameters  
myCommand.Parameters.Add("@Rowcount",SqlDbType.Int); 
myCommand.Parameters["@Rowcount"].Direction=ParameterDirection.Output; 
myCommand.ExecuteNonQuery(); 
DataAdapter.SelectCommand = myCommand; 
if (MyDataSet!=null) 
{ DataAdapter.Fill(MyDataSet,"table"); } 
DataGrid1.DataSource=MyDataSet; DataGrid1.DataBind(); // Gets the stored procedure output parameters  
Label1.Text=myCommand.Parameters["@Rowcount"].Value.ToString(); 
if (myConnection.State == ConnectionState.Open) { myConnection.Close(); 
} 
} 

Related articles: