How to update whole column in sql server table - c#

I want to update a column values in sql server table after copying those value from some other table. i.e.
where I have tested this query but not succeeded
update subset_aminer.dbo.sub_aminer_paper
set sub_aminer_paper.p_abstract =
(select aminer_paper.p_abstract
from aminer.dbo.aminer_paper
where pid IN (86257, 116497, 119248, 135555, 147554,
149720, 173254, 191333, 196650, 196656,
.....long list of other values ......
1727408, 1737809, 2034956)
)
I have to copy data from other database table to my destination database table. So that's y using subset_aminer.dbo.subset_aminer_paper.p_abstract and aminer.dbo.aminer_paper.p_abstract
Please help with acknowledgements. Thanks

update subset_aminer.dbo.sub_aminer_paper SI
set SI.p_abstract = AP.p_abstract
from aminer.dbo.aminer_paper AP
where AP.pid IN (86257, 116497, 119248, 135555, 147554,
149720, 173254, 191333, 196650, 196656,
.....long list of other values ......
1727408, 1737809, 2034956) AND AP.ID = SI.ID

Just a suggestion,
UPDATE subset_aminer.dbo.sub_aminer_paper
SET p_abstract=aminer.dbo.aminer_paper.p_abstract
FROM aminer.dbo.aminer_paper
WHERE subset_aminer.dbo.sub_aminer_paper.pid IN (86257, 116497, 119248, 135555, 147554,
149720, 173254, 191333, 196650, 196656,
.....long list of other values ......
1727408, 1737809, 2034956)

Related

Modify Ms-Access Table Structure

I have an access table with certain structure and I want to copy it to a table with a different structure. The structure of the original table is:
col1-ddate(datetime)
col2-type(text)
col3-vvalue(number).
Each 3 rows have the same date. The type has repeated 3 values(sys, dia, pul).
Now I want to insert this table data to a new(temporary) table which has the following structure
col1-ddate(datetime)
col2-sys(number)
col3-dia(number)
col4-Pul(number)
How can I do that?
If I've understood correctly, a SQL query using conditional aggregation should achieve what you are looking for, grouping by the datetime field, e.g.:
select
col1-ddate,
max(iif(col2-type = "sys", col3-vvalue, null)) as col2-sys,
max(iif(col2-type = "dia", col3-vvalue, null)) as col3-dia,
max(iif(col2-type = "pul", col3-vvalue, null)) as col4-pul
into
NewTemporaryTable
from
YourTable
group by
col1-ddate
Change YourTable to the name of your existing table.

how get datagrdiviewComboboxColumn value member?

i have a small project in c#, in one of my forms i have a datagridview with 3 columns one of the columns is comboboxcolumn that bind with a sql server table id and name, i want to insert the datagridview values into another table in the comboboxcolumn i want to insert the id not a name, anyone can tel me how to do that please? this is my insert code
`
for (int i = 0; i < dgv_student.Rows.Count; i++)
{
sc.add_student(dgv_student.Rows[i].Cells[0].Value.ToString(),
Convert.ToInt32(dgv_student.Rows[i].Cells[1].Value),
dgv_student.Rows[i].Cells[2].Value.ToString());
}
`
the cell[1] the the combobox that display a name not the id.
In your example you have :
Name ID
X X
As your database set. When you are getting this from your database you're probably doing :
myDataGridView.DataSource = GetAllFromMyDatabase(); // Select * from stuff
myDataGridView.DataBind();
Giving you all three columns, and the value. Now, if you want to insert only one column, why not just filter the data you're getting from your database/gridview ?
myComboBox.DataSource = GetOnlyIDFromMyDatabaseOrMyDataGrid(); // Select ID from Stuff
myComboBox.DataBind();
If you're binding your asp.net control with only the data you need, rather than getting everything and then filter, you will have less overhead to think about.

How to Update one table by another table datas using storedprocedure?

I have a Table named Dummywith marks and student id (3 mark fields are there). I have another one table Applicantdetails this table also contains mark fields. what I want to do is I want to updates Dummy tables marks to Applicantdetails table's marks as per student id. I want to do this by mssql Storedprocedure. Any way to achieve it. If we write in code wise it should be like this
qry="select Applicantid,mark1,mark2,mark3 from Dummy"
//saved result to Datatable dt
foreaach(DataRow. rows in dt.rows)
{
string id=Convert.ToString(row["ApplicantID"].tostring();
string mark1=Convert.ToString(row["ApplicantID"].tostring();
string mark2=Convert.ToString(row["ApplicantID"].tostring();
string mark3=Convert.ToString(row["ApplicantID"].tostring();
qry="update Applicantdetails set Mark1=mark1,Mark2=Mark2,Mark3=Mark3
where ApplicantID=id";
}
This format I want to bring in storedprocedure..Please help me
Your Stored procedure would receive #applicationid ? Otherwise it would update all, Create a stored procedure with the following SQL
UPDATE A
SET Mark1= d.mark1, Mark2 = d.mark2, Mark3= d.mark3
FROM ApplicationDetail A
JOIN Dummy d on d.Applicationid = A.Applicationid

Cant add rows to data source due to identity conflict

I have a simple VS 2012 C# form with a data grid control bound to a binding source. The SQL Server data source that this is bound to has an identity column (ID) that is also the primary key.
In the data set properties for this ID field, I have AutoIncrement = true, AutoIncrement Seed = -1 (default) and AutoIncrementStep = -1 (default)
I cannot save a new row to the database.
If I add a new record using the tool strip, clear the ID field, then click the save icon I get this exception: “Cannot insert explicit value for identity column in table xxxx when IDENTITY INSERT is set to off”. If I leave the auto generated value of “-1” in the field, I get the same exception.
The code attached to the save button:
private void tblClassificationBindingNavigatorSaveItem_Click(object sender, EventArgs e)
{
this.Validate();
this.tblClassificationBindingSource.EndEdit();
this.tableAdapterManager.UpdateAll(this.exportComplianceSISVTDataSet);
}
Executing the last step results in the exception.
Some forum respondents recommend setting IDENTITY INSERT to “ON” as a workaround but many advise against this.
I believe you are binding the data from Sql server table. Set the IDENTITY property in the SQL Server Engine itself.That is on your table in the Server.
Set the Seed to 1 and Increment to 1.
More on Identity: Click here
SQL Fiddle Demo
I had exactly this problem. Setting Identity_Insert to ON for the table did not change the error, and created inconsistent behaviour in SQL Server Management Studio. When inserting records with the identity field defined, records were apparently inserted successfully but could not be seen in results from a select statement.
I solved the problem by changing the Update and Insert statements defined in the InitAdapter function in DataSetDesigner.cs to exclude the Identity field. An example is shown below, where ID is the Identity field for the Update command.
//this._adapter.UpdateCommand.CommandText = #"UPDATE [dbo].[Stopwords] SET [ID] = #ID, [Stopword] = #Stopword, [DateAdded] = #DateAdded WHERE (([ID] = #Original_ID) AND ([Stopword] = #Original_Stopword) AND ((#IsNull_DateAdded = 1 AND [DateAdded] IS NULL) OR ([DateAdded] = #Original_DateAdded)));
//SELECT ID, Stopword, DateAdded FROM Stopwords WHERE (Stopword = #Stopword)";
this._adapter.UpdateCommand.CommandText = #"UPDATE [dbo].[Stopwords] SET [Stopword] = #Stopword, [DateAdded] = #DateAdded WHERE (([ID] = #Original_ID) AND ([Stopword] = #Original_Stopword) AND ((#IsNull_DateAdded = 1 AND [DateAdded] IS NULL) OR ([DateAdded] = #Original_DateAdded)));
SELECT ID, Stopword, DateAdded FROM Stopwords WHERE (Stopword = #Stopword)";
As these changes are in autogenerated code, they will need to be reapplied if the dataset code is regenerated.

DataRelation Insert and ForeignKey

I have a winforms application with two DataGridViews displaying a master-detail relationship from my Person and Address tables. Person table has a PersonID field that is auto-incrementing primary key. Address has a PersonID field that is the FK.
I fill my DataTables with DataAdapter and set Person.PersonID column's AutoIncrement=true and AutoIncrementStep=-1. I can insert records in the Person DataTable from the DataGridView. The PersonID column displays unique negative values for PersonID. I update the database by calling DataAdapter.Update(PersonTable) and the negative PersonIDs are converted to positive unique values automatically by SQL Server.
Here's the rub. The Address DataGridView show the address table which has a DataRelation to Person by PersonID. Inserted Person records have the temporary negative PersonID. I can now insert records into Address via DataGridView and Address.PersonID is set to the negative value from the DataRelation mapping. I call Adapter.Update(AddressTable) and the negative PersonIDs go into the Address table breaking the relationship.
How do you guys handle primary/foreign keys using DataTables and master-detail DataGridViews?
Thanks!
Steve
EDIT:
After more googling, I found that SqlDataAdapter.RowUpdated event gives me what I need. I create a new command to query the last id inserted by using ##IDENTITY. It works pretty well. The DataRelation updates the Address.PersonID field for me so it's required to Update the Person table first then update the Address table. All the new records insert properly with correct ids in place!
Adapter = new SqlDataAdapter(cmd);
Adapter.RowUpdated += (s, e) =>
{
if (e.StatementType != StatementType.Insert) return;
//set the id for the inserted record
SqlCommand c = e.Command.Connection.CreateCommand();
c.CommandText = "select ##IDENTITY id";
e.Row[0] = Convert.ToInt32( c.ExecuteScalar() );
};
Adapter.Fill(this);
SqlCommandBuilder sb = new SqlCommandBuilder(Adapter);
sb.GetDeleteCommand();
sb.GetUpdateCommand();
sb.GetInsertCommand();
this.Columns[0].AutoIncrement = true;
this.Columns[0].AutoIncrementSeed = -1;
this.Columns[0].AutoIncrementStep = -1;
You need to double click the relationship in the dataset designer, and select Cascade Updates. When your real SQL server generated PK values for your Person table are generated, it will automatically set the foreign key values in the address table as well.
You don't need to do any of that RowUpdated event stuff. Its built into the dataset functionality.
I had a similar problem, but my solution was a little different.
#Noel Kennedy: Your solution does not work with SQL Server 2005 CE, because it doesn't support multiple statements and the TableAdapter won't generate the refresh code needed to update the autoincrement columns in the parent table.
NOTE: You still need Cascade Updates in the relationship so the child tables get updated.
I also add a method in my TableAdapter, which is generic enough to just copy/paste in all your parent TableAdapters. The only thing that I change is the identity row type and index (if needed). I also add a query to the TableAdapter called GetIdentity(). You can add it to the TableAdapter in the dataset designer by adding a scalar query with sql="SELECT ##IDENTITY;"
Now the custom function is:
public int InsertAndRefresh(System.Data.DataTable dataTable)
{
int updated = 0;
System.Data.DataRow[] updatedRows = dataTable.Select("", "", System.Data.DataViewRowState.Added);
bool closed = (this.Connection.State == System.Data.ConnectionState.Closed);
if (closed)
this.Connection.Open();
foreach (System.Data.DataRow row in updatedRows)
{
updated+=this.Adapter.Update(new global::System.Data.DataRow[] { row });
decimal identity = (decimal)this.GetIdentity();
row[0] = System.Decimal.ToInt64(identity);
row.AcceptChanges();
}
if (closed)
this.Connection.Close();
return updated;
}
You want to call this on the parent first. Then do everything as usual (update parent and then children).
Cheers!

Categories