Need to insert a data row multiple times in the database - asp.net

I have two data tables in sql. I need to insert data feom one table to another. My first data table Table1 contain data column Code,Model,Num,Qty and second table Table2 also contain the same. But I need to insert the data from table1 to table2 multiple times. If Qty in Table1 is 4 then, insert the data of
Table1 for 4 times according to the quantity.
protected void Button15_Click3(object sender, EventArgs e)
{
for (int i = 0; i < 4; i++)
{
String str1 = "insert into Table2(Code, Model, Num, Qty) select Code, Model, Num, Qty from Table1;";
SqlCommand xp1 = new SqlCommand(str1, con);
con.Open();
SqlDataAdapter da1 = new SqlDataAdapter();
da1.SelectCommand = xp1;
DataSet ds1 = new DataSet();
da1.Fill(ds1, "Code");
GridView1.DataSource = ds1;
con.Close();
}
}
}
In this program I give Number 4 manually, but I need to take it from my database qty. How can I put the SQL column name qty in the loop to insert the data at multiple time?

You can give a try like this:
private void button1_Click(object sender, EventArgs e)
{
string connetionString = null;
SqlConnection connection ;
SqlDataAdapter adapter = new SqlDataAdapter();
DataSet ds = new DataSet();
int i = 0;
int j = 0;
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password";
connection = new SqlConnection(connetionString);
try
{
connection.Open();
adapter.SelectCommand = new SqlCommand("Your SQL Statement Here", connection);
adapter.Fill(ds);
connection.Close();
for(j=0;j<=ds.Tables[0].Rows.Count;j++){
for (i = 0; i <= Convert.ToInt32(ds.Tables[0].Rows[j]["Qty"].ToString()); i++)
{
String str1 = "insert into Table2(Code, Model, Num, Qty)
select Code, Model, Num, Qty from Table1;";
SqlCommand xp1 = new SqlCommand(str1, con);
con.Open();
SqlDataAdapter da1 = new SqlDataAdapter();
da1.SelectCommand = xp1;
DataSet ds1 = new DataSet();
da1.Fill(ds1, "Code");
GridView1.DataSource = ds1;
con.Close();
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
I hope it is clear now. !

As pointed out in the comments, duplicating rows isn't a good idea without a primary key on both the source and destination tables, as otherwise identification of rows will become problematic.
You haven't mentioned whether you want to copy just one row, multiple rows, or the whole table N times over, but assuming the latter, bulk IO jobs like this is better suited to doing the whole operation within the database server, in order to reduce the IO transferring data back and forth between your app and the database.
Assuming both tables are in the same database, here's a way you can do this with a row-duplicating recursive CTE. If you need to control the #CopyCount from C#, just bind it as an integer and execute it with SqlCommand.ExecuteNonQuery:
DECLARE #CopyCount INT = 10;
with cteRowGen AS
(
SELECT 1 AS RowNum
UNION ALL
SELECT RowNum + 1
FROM cteRowGen
WHERE RowNum < #CopyCount
)
insert into Table2(Code,Model,Num,Qty)
select Code,Model,Num,Qty
from table1 CROSS JOIN cteRowGen;

Like StuartLC pointed out, CTE is the way to go.
Here's a version that will read the QTY from your table1
It will also insert 1 for the Qty in Table2, and not 4
DECLARE #Cnt INT = (SELECT Qty FROM Table1);
WITH data AS (
SELECT 1 AS RowCnt
UNION ALL
SELECT RowCnt + 1
FROM data
WHERE RowCnt < #Cnt
)
INSERT INTO Table2
SELECT Code, Model, Num, 1 as Qty
FROM Table1 a
CROSS JOIN data

Related

Store multiple items in a single table column in SQL Server database

Currently I have
public void bindgrid()
{
SqlConnection conn = new SqlConnection("Data Source = 'PAULO'; Initial Catalog=ShoppingCartDB;Integrated Security =True");
SqlCommand cmd = new SqlCommand("select p.[name], cd.CustomerName, cd.CustomerEmailID,cd.CustomerPhoneNo,cd.CustomerAddress,cd.TotalPrice,cd.OrderDateTime, cd.PaymentMethod FROM CustomerDetails cd Inner Join CustomerProducts cp ON cp.CustomerID = cd.Id Inner Join Products p ON cp.ProductID = p.ProductID", conn);
SqlDataAdapter da = new SqlDataAdapter("", conn);
da.SelectCommand = new SqlCommand("select p.[name], cd.CustomerName, cd.CustomerEmailID,cd.CustomerPhoneNo,cd.CustomerAddress,cd.TotalPrice,cd.OrderDateTime, cd.PaymentMethod FROM CustomerDetails cd Inner Join CustomerProducts cp ON cp.CustomerID = cd.Id Inner Join Products p ON cp.ProductID = p.ProductID", conn);
DataSet ds = new DataSet();
da.Fill(ds, "data");
GridView1.DataSource = ds.Tables[0].DefaultView;
GridView1.DataBind();
}
and the result:
What I want to happen is that since it is in the same ID (10), would it be possible if I can have multiple values inside my Name column? like lpg, oxygen, etc?
Update: so far I got
this
I just want to store multiple values in my name column to avoid redundancy. please help
Separate your transactions from the items into two separate tables. Use the transaction ID as a foreign key in the items-purchased table. That is:
Remove the column name from your existing table
Create a new table with name and Id
Insert just one row into your existing table with a unique Id
Insert multiple rows into the new table with the same Id and the various names
So your second table would contain rows:
Id name
...
10 Carbon Dioxide
10 Industrial Oxygen
11 (a different purchase)
11 (a different purchase)
...

Get Distinct data from datatable present in webservices using linq

I want to get only single row from multiple rows with same projectname from the datatable.(Eg. if we have two rows with same projectname,the datatable should be loaded with the only one row and neglect the other one.).I have been using webservices which has the datatable.
I want to achieve this functionality using linq.
I have pasted my code for datatable.Pls help me with working code.
[WebMethod]
public DataTable Get()
{
int a = 0;
cmd = con.CreateCommand();
con.Open();
cmd = con.CreateCommand();
cmd.CommandText = " Select PROJECTNAME,COMPANY,PROJECTSTATUS,STARTEDIN,COMPLETEDIN FROM CMPPROJECT WHERE STATUS ='" + a + "'";
using (OracleDataAdapter sda = new OracleDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
dt.TableName = "CMPPROJECT";
sda.Fill(dt);
return dt;
}
}
}
You can create a DataView object which has a method ToTable in which you can pass true to parameter distinct to select distinct rows. But this has no sense to me. I would do this directly in a select query:
DataTable d = new DataTable("CMPPROJECT");
d.Columns.Add("PROJECTNAME");
d.Columns.Add("COMPANY");
d.Rows.Add(1, 1);
d.Rows.Add(1, 1);
d.Rows.Add(2, 2);
d = new DataView(d).ToTable("CMPPROJECT", true, "PROJECTNAME", "COMPANY");
Here is `linq solution:
var select = (from a in d.AsEnumerable()
select new { c1 = a["PROJECTNAME"], c2 = a["COMPANY"] }).Distinct().ToList();
d.Clear();
foreach (var item in select)
d.Rows.Add(item.c1, item.c2);

How to dislplay Data in Gridview if we have 2 Queries

i have two Queries and for that two Queries i had taken two Grid Views
select course_name , start_date, end_date, timings, fee, branch_code from coursesprovided where start_date>=Getdate() and branch_code='Ameerpet'
select course_name , start_date, end_date, timings, fee, branch_code from coursesprovided where start_date>=Getdate() and branch_code='Hi-Tech City'
During my page load i need to display the Data in Grid View.
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=(local); Initial Catalog=gateway; User Id=sa; Password=wilshire#rnd; Integrated Security=false";
//Assigning Query
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = "select course_name , start_date, end_date, timings, fee, branch_code from coursesprovided where start_date>=Getdate() and branch_code='Ameerpet'";
cmd.CommandText = "select course_name , start_date, end_date, timings, fee, branch_code from coursesprovided where start_date>=Getdate() and branch_code='Ameerpet'";
cmd.CommandType = CommandType.Text;
//Execute the COmmand
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.SelectCommand = cmd;
DataSet ds = new DataSet();
da.Fill(ds);
gvap.DataSource = ds;
gvap.DataBind();
}
is There any alternative rather than taking 2 SQLcommands, 2 SqlDataAdapter, 2 Dataset.....
Could you not just combine those two queries into one?
SELECT [course_name], [start_date], [end_date], [timings], [fee], [branch_code] FROM [coursesprovided] WHERE [start_date] > = GETDATE() AND ([branch_code] ='Ameerpet' OR [branch_code] = 'Hi-Tech City')
Keep in mind that you should avoid hard-coding field values like that if at all possible, and use parameters instead.
String branchCode1 = "Ameerpet";
String branchCode2 = "H-Tech City";
cmd.CommandText = "SELECT [course_name], [start_date], [end_date], [timings], [fee], [branch_code] FROM [coursesprovided] WHERE [start_date] > = GETDATE() AND ([branch_code] = #BranchCode1 OR [branch_code] = #BranchCode2)";
da.SelectCommand.Parameters.AddWithValue("BranchCode1", branchCode1);
da.SelectCommand.Parameters.AddWithValue("BranchCode2", branchCode2);
That block of code is simplified...you could pass in the parameter values in any way that you wanted, and you should probably keep things clean by defining the entire thing as a separate function or stored procedure, so you could pass in whatever value you wanted. I just defined the two parameters in the code for illustration purposes.

Why insert statement generates 2 rows?

I dont know why, but when I do an insert statement in my project, its generate 2 indentical rows instead of makeing just one.
why is that ?
this is my code :
if (ListBox.Items.Count != 0)
{
string username = Session["Session"].ToString();
con = new SqlConnection("Data Source=MICROSOF-58B8A5\\SQL_SERVER_R2;Initial Catalog=Daniel;Integrated Security=True");
con.Open();
string knowWhichOne = "SELECT ID FROM Users WHERE Username='" + UserOrGuest.Text + "'";
SqlCommand comm = new SqlCommand(knowWhichOne, con);
int userID = (Int32)comm.ExecuteScalar();
knowWhichOne = "SELECT ClassID FROM Users WHERE Username='" + UserOrGuest.Text + "'";
comm = new SqlCommand(knowWhichOne, con);
int classID = (Int32)comm.ExecuteScalar();
knowWhichOne = "SELECT SchoolID FROM Users WHERE Username='"+UserOrGuest.Text + "'";
comm = new SqlCommand(knowWhichOne, con);
int schoolID = (Int32)comm.ExecuteScalar();
if (RadioWords.Checked == true)
{
game = 1;
}
else
{
game = 2;
}
string arr = "";
for (int i = 0; i < ListBox.Items.Count; i++)
{
arr += ListBox.Items[i] +",";
}
string sqlqueryString = "INSERT INTO HistoryOfGames (GameID, UserID, LengthOfArray, NumberOfErrors, ClassID, SchoolID,Arrayarray) VALUES (#GameID, #UserID, #LengthOfArray, #NumberOfErrors, #ClassID, #SchoolID, #Arrayarray);" + "SELECT SCOPE_IDENTITY()";
SqlCommand commandquery = new SqlCommand(sqlqueryString, con);
commandquery.Parameters.AddWithValue("GameID", game);
commandquery.Parameters.AddWithValue("UserID", userID);
commandquery.Parameters.AddWithValue("LengthOfArray", HowMany.Text);
commandquery.Parameters.AddWithValue("NumberOfErrors", 0);
commandquery.Parameters.AddWithValue("ClassID", classID);
commandquery.Parameters.AddWithValue("SchoolID", schoolID);
commandquery.Parameters.AddWithValue("Arrayarray", arr);
commandquery.ExecuteNonQuery();
int IdOfRecentHistoryGame = (int)(decimal)commandquery.ExecuteScalar();
con.Close();
Response.Redirect("NowPlay.aspx?ID="+ IdOfRecentHistoryGame);
}
You're running it twice, ExecuteNonQuery() and ExecuteScalar(). Get rid of the ExecuteNonQuery().
you do
commandquery.ExecuteNonQuery();
then right after
int IdOfRecentHistoryGame = (int)(decimal)commandquery.ExecuteScalar();
you do execute it twice
and don't forget to check for sql injection in your code...
I'd check two things:
see how many times this statement is executed (try setting a breakpoint to verify that the code is only run once)
see if there are any triggers in the database that might cause an extra record to be inserted
I had the same problem,I handled it this way.not professional but it works:
Dim x As Boolean = True
If x = True Then
here goes your code to insert to database.
End If
x = False

How to make Oracle procedure return result sets

SQL Server procedure can return result sets. I have a table emp(emp__id, emp__name, ...). The procedure below will return a list of employees that matched with the name provided.
CREATE OR REPLACE PROCEDURE get_employee_by_name ( #name VARCHAR(100) )
AS
SELECT emp_id, emp_name
FROM emp
WHERE emp_name = #name;
So in the client code, to get the data I use ADO.NET.
SQLDataAdapter adapter = new SQLDataAdapter("get_employee_by_name", cnString);
SQLDataAdapter.SelectCommand.CommandType = CommandType.StoredProcedure;
DataTable dt = new DataTable("employee");
adapter.Fill(dt);
How can I code equivalently in PL/SQL?
Use a Ref cursor for the Stored Procedure:
http://www.oradev.com/ref_cursor.jsp
For the client part use the Oracle Data Provider. You can download it from Oracle and the syntax is similar to the SQLDataAdapter. Something like this:
OracleDataAdapter da = new OracleDataAdapter();
da.SelectCommand = new OracleCommand("get_employee_by_name", Connection);
OracleParameter prm = da.SelectCommand.Parameters.Add("pName", OracleDbType.VarChar2);
prm.Direction = ParameterDirection.Input;
prm.Value = "MyName";
prm = da.SelectCommand.Parameters.Add("pResult", OracleDbType.RefCursor);
prm.Direction = ParameterDirection.Output;
DataTable dt = new DataTable();
da.Fill(dt);

Resources