| Topic : SQL Server Programming |
|
|
|
|
Activity:
Question posted: 12 02 2008 08:50:49 +0000,
7 answers, 1739 views, last activity
07 06 2010 20:18:08 +0000
|
|
Hi all,
I'm developing a simple project using C#.net 2005 with SQL Server 2000. In my project, I need to retrieve the data from SQL database in my page with the help of stored procedure. I've no idea that how to do?
Please help me.
Create an ASP.NET Project and Add Controls
In this section, you create an ASP.NET project and build the basic user interface. Note that these steps use Microsoft Visual C# .NET code. To create the project, follow these steps:
- Click Start, point to Programs, point to Microsoft Visual Studio .NET, and then click Microsoft Visual Studio .NET.
- On the Visual Studio .NET Start page, click New Project.
- In the New Project dialog box, click Visual C# Projects under Project Types, and then click ASP.NET Web Application under Templates.
- In the Name box, type a name for your Web application, and then click OK.
- Add the following server controls to the Web Form, and set the properties as they are listed in the table:
Collapse this table
Control ID Property Text Property Label lblLastName Type the Author's Last Name: TextBox txtLastName % Button btnGetAuthors Get Authors Label lblRowCount (Row Count) - Drag a DataGrid server control from the toolbox to the Web Form, and then set the Name property to GrdAuthors.
- Right-click the grid, and then click Autoformat.
- Click Professional 1 for the scheme, and then click OK.
Create the GetAuthorsByLastName Stored Procedure
Use the following Transact-SQL code to create the GetAuthorsByLastName stored procedure:
Use Pubs
Go
Create Procedure GetAuthorsByLastName (@au_lname varchar(40), @RowCount int output)
as
select * from authors where au_lname like @au_lname;
/* @@ROWCOUNT returns the number of rows that are affected by the last statement. */
select @RowCount=@@ROWCOUNT
This code includes two parameters: @au_lname and @RowCount. The @au_lname parameter is an input parameter that obtains the search string to perform a "like" search in the Authors table. The @RowCount parameter is an output parameter that uses the @@ROWCOUNT variable to obtain the affected rows.
Create and Run the Stored Procedure
To access SQL Server databases, you must import the System.Data.SqlClient namespace, which provides new objects such as the SqlDataReader and the SqlDataAdapter objects. You can use SqlDataReader to read a forward-only stream of rows from a SQL Server database. DataAdapter represents a set of data commands and a database connection that you can use to fill the DataSet object and to update a SQL Server database.
ADO.NET also introduces the DataSet object, which is a memory-resident representation of data that provides a consistent, relational programming model regardless of the data source. The code in this section uses all of these objects.
- Double-click the Web Form.
- Add the following code (the using directives) to the Declaration section of your Web Form, which appears at the top of the Code window:
using System.Data; using System.Data.SqlClient;
- To make sure that the stored procedure exists and to create a new stored procedure, use a SqlCommand object with a SqlDataReader object. You can use SqlCommand to run any SQL commands against the database. Then call the ExecuteReader method of SqlCommand to return SqlDataReader, which contains matching rows for your query.
Add the following code in the Page_Load event of the Web Form:private void Page_Load(object sender, System.EventArgs e) { // Only run this code the first time the page is loaded. // The code inside the IF statement is skipped when you resubmit the page. if (!IsPostBack) { //Create a connection to the SQL Server; modify the connection string for your environment //SqlConnection MyConnection = new SqlConnection("server=(local);database=pubs;Trusted_Connection=yes"); SqlConnection MyConnection = new SqlConnection("server=(local);database=pubs;UID=myUser;PWD=myPassword;"); // Create a Command object, and then set the connection. // The following SQL statements check whether a GetAuthorsByLastName // stored procedure already exists. SqlCommand MyCommand = new SqlCommand("select * from sysobjects where id = object_id(N'GetAuthorsByLastName')" + " and OBJECTPROPERTY(id, N'IsProcedure') = 1", MyConnection); // Set the command type that you will run. MyCommand.CommandType = CommandType.Text; // Open the connection. MyCommand.Connection.Open(); // Run the SQL statement, and then get the returned rows to the DataReader. SqlDataReader MyDataReader = MyCommand.ExecuteReader(); // If any rows are returned, the stored procedure that you are trying // to create already exists. Therefore, try to create the stored procedure // only if it does not exist. if(!MyDataReader.Read()) { MyCommand.CommandText = "create procedure GetAuthorsByLastName" + " (@au_lname varchar(40), select * from authors where" + " au_lname like @au_lname; select @RowCount=@@ROWCOUNT"; MyDataReader.Close(); MyCommand.ExecuteNonQuery(); } else { MyDataReader.Close(); } MyCommand.Dispose(); //Dispose of the Command object. MyConnection.Close(); //Close the connection. } // Add the event handler to the Button_Click event. this.btnGetAuthors.Click += new System.EventHandler(this.btnGetAuthors_Click); } - Call the stored procedure in the Click event of the btnGetAuthors button, and then use the SqlDataAdapter object to run your stored procedure. You must create parameters for the stored procedure and append it to the Parameters collection of the SqlDataAdapter object.
Add the following code after the Page_Load event:private void btnGetAuthors_Click(object sender, System.EventArgs e) { //Create a connection to the SQL Server; modify the connection string for your environment. //SqlConnection MyConnection = new SqlConnection("server=(local);database=pubs;Trusted_Connection=yes"); SqlConnection MyConnection = new SqlConnection("server=(local);database=pubs;UID=myUser;PWD=myPassword;"); //Create a DataAdapter, and then provide the name of the stored procedure. SqlDataAdapter MyDataAdapter = new SqlDataAdapter("GetAuthorsByLastName", MyConnection); //Set the command type as StoredProcedure. MyDataAdapter.SelectCommand.CommandType = CommandType.StoredProcedure; //Create and add a parameter to Parameters collection for the stored procedure. MyDataAdapter.SelectCommand.Parameters.Add(new SqlParameter("@au_lname", SqlDbType.VarChar, 40)); //Assign the search value to the parameter. MyDataAdapter.SelectCommand.Parameters["@au_lname"].Value = (txtLastName.Text).Trim(); //Create and add an output parameter to the Parameters collection. MyDataAdapter.SelectCommand.Parameters.Add(new SqlParameter("@RowCount", SqlDbType.Int, 4)); //Set the direction for the parameter. This parameter returns the Rows that are returned. MyDataAdapter.SelectCommand.Parameters["@RowCount"].Direction = ParameterDirection.Output; //Create a new DataSet to hold the records. DataSet DS = new DataSet(); //Fill the DataSet with the rows that are returned. MyDataAdapter.Fill(DS, "AuthorsByLastName"); //Get the number of rows returned, and assign it to the Label control. //lblRowCount.Text = DS.Tables(0).Rows.Count().ToString() & " Rows Found!" lblRowCount.Text = MyDataAdapter.SelectCommand.Parameters[1].Value + " Rows Found!"; //Set the data source for the DataGrid as the DataSet that holds the rows. GrdAuthors.DataSource = DS.Tables["AuthorsByLastName"].DefaultView; //NOTE: If you do not call this method, the DataGrid is not displayed! GrdAuthors.DataBind(); MyDataAdapter.Dispose(); //Dispose the DataAdapter. MyConnection.Close(); //Close the connection. } - In Solution Explorer, right-click the .aspx page, and then click Set as Start Page.
- Save the project, and then click Start in Visual Studio .NET. Notice that the project is compiled and that the default page runs.
- Type the author's last name in the text box, and then click Get Author. Notice that the stored procedure is called and that the returned rows populate the DataGrid.
You can provide SQL Server-type search strings such as G%, which returns all the authors by last names that start with the letter "G."
Troubleshooting
- If you cannot connect to the database, make sure that the ConnectionString properly points to the server that is running SQL Server.
- If you can connect to the database, but if you experience problems when you try to create the stored procedure, make sure that you have the correct permissions to create stored procedures in the database to which you are connecting.
Hi Dude !
This is a simple way to get Data from SQL server Strore Procedure by passing some Input Based.
-------------1---------------------
CREATE PROCEDURE [dbo].[Login_Employee_GET_SP]
(
@M_USER_ID VARCHAR(10)=NULL,
@M_PASSWORD VARCHAR(20)=NULL
)
AS
BEGIN
SELECT EMP_WINDOW_ID,EMP_FIRST_NAME,EMP_LAST_NAME, EMP_EMAIL,
DESIGNATION,LTRIM(RTRIM(LOCATION)) AS LOCATION ,DEPARTMENT,REPORT_TO,ACCESS
FROM TBL_DEL_EMPLOYEE
WHERE EMP_WINDOW_ID = @M_USER_ID AND EMP_PASSWORD=@M_PASSWORD AND DELETED=0
END
-----------1---------------
-------------2-------------------
1) Cretae a Simple Function This will return DataSet Objects.
public DataSet fncGetPrcgetUserDetails(Hashtable objHashParams)
{
SqlConnection mObjclsConnection = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["ConStr"]); // Read Config Vaible
DataSet mObjDataSet = new DataSet();
SqlCommand mObjCmd = new SqlCommand();
SqlDataAdapter sqlAdap = new SqlDataAdapter(mObjCmd);
try
{
SqlParameter mObjParam =new SqlParameter();
mObjCmd.Connection = mObjclsConnection;
mObjCmd.CommandText = "Login_Employee_GET_SP"; //Store Procedure Name
mObjCmd.CommandType = CommandType.StoredProcedure;
if ((objHashParams["UserID"] == null)) //Input Variable
{
mObjParam = new SqlParameter("@M_USER_ID", DBNull.Value);
}
else
{
mObjParam = new SqlParameter("@M_USER_ID", objHashParams["UserID"]);
}
mObjParam.DbType = DbType.String;
mObjCmd.Parameters.Add(mObjParam);
mObjParam = null;
if ((objHashParams["Password"] == null)) //Input Variable
{
mObjParam = new SqlParameter("@M_PASSWORD", DBNull.Value);
}
else
{
mObjParam = new SqlParameter("@M_PASSWORD", objHashParams["Password"]);
}
mObjParam.DbType = DbType.String;
mObjCmd.Parameters.Add(mObjParam);
mObjParam = null;
sqlAdap.Fill(mObjDataSet);
return mObjDataSet;
}
catch (Exception Ex)
{
throw Ex;
}
finally
{
mObjclsConnection = null;
}
}
-------------2---------------------
using System.data.sqlclient;
using System.data;
sqlcommand sqlcom
sqlconnection sqlcon;
sqlDataAdapter adpcomm;
dataset da=new dataset;
string sqry;
sqry="YourStoredProcedure Name";
Sqlcom=new sqlcommand(sqry,sqlcon);
sqlcom.commandType=commandtype.storedProcedure;
sqlcom.parameters.addWithValue(if Any Parameters u got the Synatax is "@ppp",Value eg 1,a,1.1)
adpcom=new SqldataAdapter(sqlcom)
adpcomm.fill(ds,"tableName)
public Result GetBill(out string BillXML)
{
Result retVal;
retVal.Message = "";
retVal.Status = false;
BillXML = null;
try
{
SqlXmlCommand cmd = new SqlXmlCommand(@DataBaseXml);
cmd.CommandType = SqlXmlCommandType.Sql;
cmd.CommandText = "exec [GetBill]";
Stream output = cmd.ExecuteStream();
StreamReader reader = new StreamReader(output);
BillXML = reader.ReadToEnd();
BillXML = "<Admin>" + BillXML + "</Admin>";
retVal.Status = true;
return retVal;
}
catch (Exception ex)
{
Utility.ErrorLog.WriteToFile(errorfile, "GetBill", ex.Message);
retVal.Status = false;
return retVal;
}
}
Hi all these are one method and you can use SQLHelper which is a standard helper file provided by microsoft
and which will be very much useful for using it in the Data logic layer of all ur .net applications.
code will be like this :
include this sqlhelper.cs : http://www.koders.com/csharp/fidD4121D6E4BCA2DAB656D770903FECBFF7427D242.aspx?s=mdef%3Ainsert
to your solution :
using Helper.SQLHelper;
SqlParameter[] Param = new SqlParameter[2];
Param[0] = new SqlParameter("@number", objBLL.nNo);
Param[1] = new SqlParameter("@name", objBLL.strname);
DataSet dsstudentdetails = new DataSet();
dsstudentdetails = SqlHelper.ExecuteDataset(strSQLConnectionString, CommandType.StoredProcedure, "Getstudentdetails", Param);
if (dsstudentdetails.Tables.Count > 0)
{
return dsstudentdetails;
}
else
{
return dsstudentdetails;
}
here objbll is the business logic layer object for which u can pass data from ur presentation layer and the total bll is passed to the function
Just making it more appropriate
SqlConnection theCon;
theCon = "<your Connection>";
SqlCommand theCommand;
theCommand = new SqlCommand("PR_MMS_ISSUESUMMARY_MAX", theCon);
theCommand.CommandType = CommandType.StoredProcedure;
theCommand.CommandTimeout = 180 //in secs
theCommand.Parameters.Add("@fromdate", SqlDbType.DateTime);
theCommand.Parameters["@fromdate"].Value = fromdate.Value.ToString("yyyy-MM-dd") ;
theCommand.Parameters.Add("@todate",SqlDbType.DateTime);
theCommand.Parameters["@todate"].Value = todate.Value.ToString("yyyy-MM-dd") ;
theCommand.Parameters.Add("@loggedstationid", SqlDbType.Int);
theCommand.Parameters["@id"].Value = id
theDs=new DataSet();
SqlDataAdapter theAdapater = new SqlDataAdapter(theCommand);
try
{
theAdapater.Fill(theDs);
return theDs;
}
catch(SqlException ex){
//Do what u like;
}
finally{
theCon.Close();
theCon.Dispose();
theCommand.Dispose();
}
SqlConnection theCon;
theCon = "<your Connection>";
SqlCommand theCommand;
theCommand = new SqlCommand("PR_MMS_ISSUESUMMARY_MAX", theCon);
theCommand.CommandType = CommandType.StoredProcedure;
theCommand.CommandTimeout = 180 //in secs
theCommand.Parameters.Add("@fromdate", SqlDbType.DateTime);
theCommand.Parameters["@fromdate"].Value = fromdate.Value.ToString("yyyy-MM-dd") ;
theCommand.Parameters.Add("@todate",SqlDbType.DateTime);
theCommand.Parameters["@todate"].Value = todate.Value.ToString("yyyy-MM-dd") ;
theCommand.Parameters.Add("@loggedstationid", SqlDbType.Int);
theCommand.Parameters["@id"].Value = id
theDs=new DataSet();
SqlDataAdapter theAdapater = new SqlDataAdapter(theCommand);
theAdapater.Fill(theDs);
return theDs;
|
|
|
|
|
|
|
|
|
|
|
|
Hi friends, I'm new to Visual C++. And I want to know the real world applications which are developed by using VC++. If you know the answer, please post your answer here or http:\\computerprogramminghelp.blogspot.com |
How to change the image size when hover the mouse? |
How to call a stored procedure using SQL Server 2000 and C#.NET? |