Insert and select within same sp? - c#

Here I came up with situation where I want insert records in temp temple and again want to dispaly that record to user.
I have created one sp in that sp created temp table, added record to that table and select record from temp table.How to show record to user in interface?
ExecuteNOnquery is used for inserting record and ExecuteReader is is used for selecting record.
Withing same sp,I have insert and select.So how to do that in code behind?

You should use ExecuteReader.
All it does - sends string of CommandText to server, executes it, and then builds SqlDataReader to read from.
So if your CommandText is a call to stored procedure - this procedure will be executed (so it will insert your data and select it back) and returned data will be available in SqlDataReader.
See MSDN for reference to ExecuteReader

You could do something like this
using(var con = new SqlConnection(conStr))
{
var cmd = new SqlCommand("MY_SP",con);
cmd.CommandType = CommandType.StoredProcedure;
var da = new SqlDataAdapter(cmd);
var ds = new DataSet();
da.Fill(ds);
if(ds.Tables.Count > 0)
{
foreach(var dr in ds.Tables[0].Rows)
{
// Do stuffs with dr
}
}
}

Related

Calling a stored procedure results in an incorrectly empty DataTable

I have a functioning stored procedure which returns the correct data when executed manually. There are several rows of data in the output. However, the following code I have is always resulting in no rows of data being added to the DataTable.
var commandString = string.Format(#"EXEC MyStoredProcedure {0}", SomeParameter);
var dataTable = new DataTable();
using (var connection = new SqlConnection(ConnectionString))
{
connection.Open();
using (var adapter = new SqlDataAdapter(commandString, ConnectionString))
{
using (new SqlCommandBuilder(adapter))
{
adapter.Fill(dataTable);
adapter.Update(dataTable);
}
}
}
var result = (from DataRow row in dataTable.Rows
select new MyModelClass
{
SomeString = (string) row["SomeString"],
SomeValue = (string) row["SomeValue"],
}).ToList();
Debug.WriteLine("Results: " + result.Count);
I am not sure why the code is resulting in no rows of data. Where am I going wrong? I suspect it is because I have an incorrect understanding of how DataTable works. How should I fix the code?
Basically, your code should look something like this:
string ConnectionString = "<Your connection string here>";
string procedureName = "<your stored procedure name here>";
string ParamName = "#<Parameter name>"; // NOTE: the '#' is INSIDE the string!
DataSet ds = new DataSet();
using (var connection = new SqlConnection(ConnectionString))
{
var cmd = new SqlCommand(procedureName, connection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(ParamName, SqlDbType.Int).Value = 5;
using (var adapter = new SqlDataAdapter(cmd))
{
adapter.Fill(ds);
}
}
Sorry to be late to the party but I just want to confirm something.
I noticed that in the OP the asker uses the adapter to fill a DataTable
In the accepted answer, however, the adapter is used to fill a DataSet
Well, that's great - I also discovered this myself. The DataTable will contain 0 rows ase well as 0 columns, but use it to fill a DataSet instead, and it works fine.
So the real question here is: Why does it work with a DataSet when it doesn't with a DataTable?
I have a suspicion and I'm really here to try and prove it right or wrong. In my case I found that the SP started returning this weird empty DataTable as soon as my SP contained anything like a DELETE or an INSERT. In my case, where the original SP was just a simple SELECT from some data, I had to add some complexity which meant I first had to populate a Table Variable using INSERTs, and then SELECT from that. And that's when I ran into this problem.
So, #user9993, if you're still around can you just tell me.... does your SP do more than just SELECT? Does it do updates or deletes even if it's just to something like a Temporary Table or a Table Variable?

Use DataTable Update() Method to Update Multiple SQL Tables?

I'm trying to update my SQL backend with data that has changed in my webform.
That data is initially fetched from SQL like so
string cs = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
SqlConnection connection = new SqlConnection(cs);
SqlCommand command = new SqlCommand("my.storedprocedure", cs);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(new SqlParameter("#customerID", custid));
command.CommandTimeout = 300;
connection.Open();
SqlDataAdapter sda = new SqlDataAdapter(command);
connection.Close();
sda.FillSchema(myDataTable, SchemaType.Source);
sda.Fill(myDataTable);
The stored procedure makes a selection
SELECT c.*
,cs.*
,p.*
,sl.*
,drl.*
FROM tableC as c
INNER JOIN tableCS as cs ON c.[custID] = cs.[custID]
INNER JOIN tableSL as sl ON cs.[custStatusID] = sl.[custStatusID]
LEFT OUTER JOIN tableP as p ON c.custID = p.custID
LEFT OUTER JOIN tableDRL as drl ON cs.custID = drl.custID
WHERE c.[custID] = #custID AND c.[EndDate] IS NULL AND cs.[EndDate] IS NULL
I then manipulate the data table that is filled with this stored procedure, call a dt.NewRow(), add values to that new row, add the row into the data table. Set fields in the previous row, etc.
My question is, when I get ready to call a SqlDataAdapter.Update(myDataTable) will the data adapter go ahead and make the update to all the tables I joined too? Based on what's in my data table?
The short answer is no - a single adapter is for a single table. You need to use a DataSet if you are using ADO.NET.
Using a DataSet:
Populating a DataSet from a DataAdapter
ADO.NET - Updating Multiple DataTables
Fill DataSet with multiple Tables and update them with DataAdapter
Using TableAdapterManager:
TableAdapterManager Overview

Update DataGrid after insert with procedure

I know this question was asked but I can't figure out why this action is so complex.
So I have a Produs table
SELECT TOP 1000 [IDProdus]
,[Denumire]
,[UM]
,[Pret]
,[IDFurnizor]
,[IDCategorie]
,[IDTipProdus]
,[OperatorAdaugare]
,[DataAdaugare]
,[OperatorModificare]
,[DataModificare]
FROM [Proiect].[dbo].[Produse]
This is my table's columns. I added via Data Sources GUI from Visual Studio a DataSet with the content of this table (no actual code wrote by me).
Now I have a procedure that will insert me a new row in this Table.
Here is the code:
private void dToolStripMenuItem_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("connection-string-here");
string Query = "spGE_getProduse_Edit"; // Stored procedure name.
int Integer;
conn.Open();
// Creating SqlCommand object
SqlCommand com = new SqlCommand(Query, conn );
// Here we declaring command type as stored procedure:
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#IDProdus", 0);
com.Parameters.AddWithValue("#Denumire ",
denumireTextBox.Text.ToString());
com.Parameters.AddWithValue("#UM ",
uMTextBox.Text.ToString());
com.Parameters.AddWithValue("#Pret ",
Double.Parse(pretTextBox.Text));
com.Parameters.AddWithValue("#IDFurnizor ",
Int16.Parse(iDFurnizorTextBox.Text));
com.Parameters.AddWithValue("#IDCategorie ",
Int16.Parse(iDCategorieCombobox.SelectedValue.ToString()));
com.Parameters.AddWithValue("#IDTipProdus ",
Int16.Parse(iDTipProdusCombobox.SelectedValue.ToString()));
com.Parameters.Add("#IDProdusScris", SqlDbType.BigInt);
com.Parameters["#IDProdusScris"].Direction =
ParameterDirection.Output;
com.ExecuteNonQuery();
conn.Close();
Integer =
Int32.Parse(com.Parameters["#IDProdusScris"].Value.ToString());
}
Now after insert I want to update myGrid with the new record. I tried
dataGridView1.Refresh(); and dataGridView1.Update();, with no result.
Is there a way to update the grid? It looks like a simple task for VS, but I couldn't find a simple solution.
What I saw only and read on MSDN looked like some very complex operations just for a simple refresh. (It was about getting the state of the row and insert the row if the state was Added).
So is there any simple way to do this, or I have to write a method that will refresh my dataGridView every time I want (I mean to re-query my table and rebuild the dataSource)
Try like this:
dataGridView1.Refresh(); and dataGridView1.Update(); will not fetch updated records from db.
Source
You can use stored procedures are pre-complied
Create Procedure Sp_getProducts
as
BEGIN
SELECT TOP 1000 [IDProdus]
,[Denumire]
,[UM]
,[Pret]
,[IDFurnizor]
,[IDCategorie]
,[IDTipProdus]
,[OperatorAdaugare]
,[DataAdaugare]
,[OperatorModificare]
,[DataModificare]
FROM [Proiect].[dbo].[Produse]
END
Use this code which Uses Using Statements
using (SqlConnection conn = new SqlConnection("connection-string-here"))
{
conn.Open();
using(SqlCommand cmd=new SqlCommand("Sp_getProducts",conn))
{
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable ds = new DataTable();
da.Fill(ds);
gridView.DataSource = ds;
gridView.DataBind();
conn.Close();
}
}
Try resetting your datasource:
dataGridView1.DataSourcce = null;
dataGridView1.DataSource = [YOUR DATASET];
dataGridView1.Refresh();
dataGridView1.Update();

Using Retrieved Data from a Parameterized SQL Query

If I'm using a parameterized query (ASP.NET with C#) in SQL, such as
var db = Database.Open("Database1");
SqlCommand cmd = new SqlCommand("SELECT * FROM pageinfo WHERE pageID = #pageID");
cmd.Parameters.AddWithValue("#pageID", 1);
And later on in the page, I want to do a foreach loop of whatever data was retrieved:
foreach(var row in ???)
What would I use (in place of the ???) to access the data I just retrieved?
Thanks.
It depends on how you execute a query.
Usually it's done by SqlCommand.ExecuteReader
For example, in your case, you can:
....
SqlDataReader reader = cmd .ExecuteReader();
while (reader.Read())
{
...
}
But there are also other ways to rertieve the data, for example using DataSet
For a complete example on how to do that can have a look on:
Using ADO.NET for beginners
You can use while iteration statement with SqlCommand.ExecuteReader instead of foreach. Take a look this;
var db = Database.Open("Database1");
SqlCommand cmd = new SqlCommand("SELECT * FROM pageinfo WHERE pageID = #pageID");
cmd.Parameters.AddWithValue("#pageID", 1);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(reader[0]);
}
reader[0] returns first row of first column and reader[1] returns first row of second column if your data has of course.

Insert rows to DataTable from SQL table

I have a Datatable in my C# program that I would like to INSERT rows from a temp table in SQL Server. The dataAdapter.FILL() method writes over the whole datatable. I need to keep the records that are in the DataTable and add records that exist in the temp table back into my DataTable.
I do not see a DA method for that, they all seem to go back to the SQL Server table except FILL. Is this possible?
How about Merging your DataTables
DataTable dttemp = new DataTable();
dataAdapter.Fill(dtTemp);
originaldatatable.Merge(dtTemp);
// Now, open a database connection using the Microsoft.Jet.OLEDB provider.
// The "using" statement ensures that the connection is closed no matter what.
using (var connection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data source=Northwind.mdb"))
{
connection.Open();
// Create an OleDbDataAdapter and provide it with an INSERT command.
var adapter = new OleDbDataAdapter();
adapter.InsertCommand = new OleDbCommand("INSERT INTO Shippers (CompanyName, Phone) VALUES (#CompanyName , #Phone)", connection);
adapter.InsertCommand.Parameters.Add("CompanyName", OleDbType.VarChar, 40, "CompanyName");
adapter.InsertCommand.Parameters.Add("Phone", OleDbType.VarChar, 24, "Phone");
adapter.Update(data);
}

Categories

Resources