Problem With Update When Updating All Rows Of A Table Through Dataset And Saving Back To Database

Feb 24, 2006

Hi,

I have an application where I'm filling a dataset with values from a table. This table has no primary key. Then I iterate through each row of the dataset and I compute the value of one of the columns and then update that value in the dataset row. The problem I'm having is that when the database gets updated by the SqlDataAdapter.Update() method, the same value shows up under that column for all rows. I think my Update Command is not correct since I'm not specifying a where clause and hence it is using just the value lastly computed in the dataset to update the entire database. But I do not know how to specify  a where clause for an update statement when I'm actually updating every row in the dataset. Basically I do not have an update parameter since all rows are meant to be updated. Any suggestions?

SqlCommand snUpdate = conn.CreateCommand();

snUpdate.CommandType = CommandType.Text;

snUpdate.CommandText = "Update TestTable set shipdate = @shipdate";

snUpdate.Parameters.Add("@shipdate", SqlDbType.Char, 10, "shipdate");

string jdate ="";

for (int i = 0; i < ds.Tables[0].Rows.Count - 1; i++)

{

jdate = ds.Tables[0].Rows[i]["shipdate"].ToString();

ds.Tables[0].Rows[i]["shipdate"] = convertToNormalDate(jdate);

}

da.Update(ds, "Table1");

conn.Close();

 

-Thanks

View 4 Replies


ADVERTISEMENT

My Dataset Is Saving Only The First Image Saved In The Database In Subsquent Rows

Mar 13, 2007

When i click upload image button when my database table has no any row, the selected image is saved(one row saved in table). If i continue and select a different image, i get no error sa if the image has been saved but when i view the images i have been saving, its strange even if i saved 10 records they all contain the first image that i saved. In short only the first image is saved the rest of the rows are just duplicates of the first row. so it basically becomes a table of ten rows but with same data rows(same image). Code is below.
Protected Sub btnupload_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Dim intLength As Integer
Dim arrContent As Byte()
If FileUpload.PostedFile Is Nothing Then
Lblstatus.Text = "No file specified."
Exit Sub
Else
Dim fileName As String = FileUpload.PostedFile.FileName
Dim ext As String = fileName.Substring(fileName.LastIndexOf("."))
ext = ext.ToLower
Dim imgType = FileUpload.PostedFile.ContentType
If ext = ".jpg" Then
ElseIf ext = ".bmp" Then
ElseIf ext = ".gif" Then
ElseIf ext = "jpg" Then
ElseIf ext = "bmp" Then
ElseIf ext = "gif" Then
Else
Lblstatus.Text = "Only gif, bmp, or jpg format files supported."
Exit Sub
End If
intLength = Convert.ToInt32(FileUpload.PostedFile.InputStream.Length)
ReDim arrContent(intLength)
FileUpload.PostedFile.InputStream.Read(arrContent, 0, intLength)
If Doc2SQLServer(txtTitle.Text.Trim, arrContent, intLength, imgType) = True Then
Lblstatus.Text = "Image uploaded successfully."
Else
Lblstatus.Text = "An error occured while uploading Image... Please try again."
End If
End If
End Sub
Protected Function Doc2SQLServer(ByVal title As String, ByVal Content As Byte(), ByVal Length As Integer, ByVal strType As String) As Boolean
Try
Dim cnn As Data.SqlClient.SqlConnection
Dim cmd As Data.SqlClient.SqlCommand
Dim param As Data.SqlClient.SqlParameter
Dim strSQL As String
strSQL = "Insert Into Images(imgData,imgTitle,imgType,imgLength,incident_id) Values(@content,@title,@type,@length,@incident_id)"
Dim connString As String = "Data Source=.SQLEXPRESS;AttachDbFilename=|DataDirectory|safetydata.mdf;Integrated Security=True;User Instance=True"
cnn = New Data.SqlClient.SqlConnection(connString)
cmd = New Data.SqlClient.SqlCommand(strSQL, cnn)
param = New Data.SqlClient.SqlParameter("@content", Data.SqlDbType.Image)
param.Value = Content
'cmd.Parameters.AddWithValue(param)
cmd.Parameters.AddWithValue("@content", Content)
 
param = New Data.SqlClient.SqlParameter("@title", Data.SqlDbType.VarChar)
param.Value = title
cmd.Parameters.Add(param)
param = New Data.SqlClient.SqlParameter("@type", Data.SqlDbType.VarChar)
param.Value = strType
cmd.Parameters.Add(param)
param = New Data.SqlClient.SqlParameter("@length", Data.SqlDbType.BigInt)
param.Value = Length
cmd.Parameters.Add(param)
cmd.Parameters.AddWithValue("@incident_id", id.Text)
cnn.Open()
cmd.ExecuteNonQuery()
cnn.Close()
Return True
Catch ex As Exception
Return False
End Try
End Function

View 1 Replies View Related

DataSet Rows Being Deleted, But After The Update , The Sql Database Is Not Updated. The Delete Rows Still In The Database.

Jun 4, 2007

 Stepping thru the code with the debugger shows the dataset rows being deleted.
 
After executing the code, and getting to the page presentation. Then I stop the debug and start the
page creation process again ( Page_Load ).    The database still has the original deleted dataset rows.
Adding rows works, then updating works fine, but deleting rows, does not seem to work.
 
The dataset is configured to send the DataSet updates to the database. Use the standard wizard to create the dataSet.
 
 
cDependChildTA.Fill(cDependChildDs._ClientDependentChild, UserId);        rowCountDb = cDependChildDs._ClientDependentChild.Count;               for (row = 0; row < rowCountDb; row++)        {           dr_dependentChild = cDependChildDs._ClientDependentChild.Rows[0];           dr_dependentChild.Delete();                      //cDependChildDs._ClientDependentChild.Rows.RemoveAt(0);           //cDependChildDs._ClientDependentChild.Rows.Remove(0);            /* update the Client Process Table Adapter*/          // cDependChildTA.Update(cDependChildDs._ClientDependentChild);      //     cDependChildTA.Update(cDependChildDs._ClientDependentChild);        }
        /* zero rows in the DataSet at this point */        /* update the Child  Table Adapter */       cDependChildTA.Update(cDependChildDs._ClientDependentChild);

View 1 Replies View Related

Saving A Stored Procedure As A Csv File Back Into A Table In The Database

Feb 25, 2008

I have a table that has 5 values that I want to MSSQL to create a csv file for. After it is created, dump that csv file back into the database as a binary file. Is this possible?

View 1 Replies View Related

Add Rows To A DataSet Without Updating The MS SQL Server?

Jan 9, 2006

I am using ASP.NET 2.0 WebForms and I was trying to use a DataSet to add rows programatically without adding the actual records to the MS SQL Server Databases. Is this possible or should I be doing this another way?
DataSet myDS = new DataSet();DataTable myTable = new DataTable("table1");myTable.Columns.Add("col1", typeof(string));myDS.Tables.Add(myTable);myTable.Rows.Add("MyValue");
Thanks.

View 1 Replies View Related

Getting Data From Dataset Back Into Database

Sep 7, 2006

I'm new at this so I apologize in advance for my ignorance.

I'm creating a website that collects dates in a calendar control (from Peter Blum). When the page containing the control loads it populates the calendar with dates from the database (that have previously been selected by the user). The user then can delete existing dates and/or add new dates.

I create a dataset when the page loads and use it to populate the calendar. When the user finishes adding and deleting dates in the calendar control I delete the original dates from the dataset and then write the new dates to the dataset. I then give execute the data adapter update command to load the contents of the dataset back into the database. This command involves using parameterized queries. For example the Insert command is:

Dim cmdInsert As SqlCommand = New SqlCommand("INSERT INTO Requests VALUES(@fkPlayerIDNumber, @RequestDate, @PostDate, @fkGroupID)", conn)

cmdInsert.Parameters.Add(New SqlParameter("@fkPlayerIDNumber", SqlDbType.Int))

cmdInsert.Parameters.Add(New SqlParameter("@RequestDate", SqlDbType.DateTime))

cmdInsert.Parameters.Add(New SqlParameter("@PostDate", SqlDbType.DateTime))

cmdInsert.Parameters.Add(New SqlParameter("@fkGroupID", SqlDbType.Int))

da.InsertCommand = cmdInsert

The update command is:

da.Update(ds, "Requests")

When I run the program I get the following error:

Parameterized Query '(@fkPlayerIDNumber int,@RequestDate datetime,@PostDate datetime,' expects parameter @fkPlayerIDNumber, which was not supplied.

I've used debug print to establish that the table in the dataset contains what it should.

I would be more than grateful for any suggestions.

View 3 Replies View Related

Saving Original SQL Database And My.Settings When Reinstalling Or Updating

Apr 27, 2007



Hello all...



I am working on a project that contains several databases in SQL and many settings. The problem I am encountering is that I want to be able to update the program for all my customers. That is no problem.

The problem I am meeting is where, when the program is updated, all the settings and all the information in the databases reverts to the default values, or the values that were compiled with the new update.

I want to be able to update their program without deleting all the settings they have.



Thanks,

Andreas Renberg

View 1 Replies View Related

Updating The Database From The Dataset

Jul 22, 2007

I am having the oddest problem. I can update the data in the dataset, but when I use the update command, or try to do a update manually it will not save the values back to the database.



public void insrtnewtime()

{

int begintime = 00;

int endtime = 23;

int countr;

int _minz;

do

{

begintime = begintime + 1;

string string_begintime_representation = begintime.ToString("00");



//now I have a valid string representations

int _year = 2007;

int _month = 1;

int _day = 1;

int _hour = int.Parse(string_begintime_representation);

_minz = 00;

//need to account for 60 minutes



do

{

//now I need to get a real nice representation to be shown for the visual display

DateTime temptime = new DateTime(_year, _month, _day, _hour, _minz, 0);

//Now I need to strip out just the time, and send it to my stored proc

string stringnewtime_rep_visual = temptime.ToString("t");

string stringnewtime_rep_visual24 = temptime.ToString("HH:mm");



this.tbl_strt_tmesTableAdapter.insrt_strt_times(stringnewtime_rep_visual24, stringnewtime_rep_visual);



_minz += 5;

}

while (_minz < 60);

countr = begintime;

} while (countr < endtime);

this.tbl_strt_tmesTableAdapter.Fill(this.lesson_plannerDataSet.tbl_strt_tmes);

try

{

tbl_strt_tmesTableAdapter.Update(lesson_plannerDataSet.tbl_strt_tmes);//this should save the values

}

catch (Exception e)

{

MessageBox.Show(e.Message);

}









}





the table adapter update, should send the values to the database, but for some reason, it is not. i can see the existing values from the database, along with my new values that i added in my loop, but those values are not being sent to the database when I invoke the update command on the data adapter.

Any help will be greatly appreciated. I am making this program for my wife who is a school teacher.

View 1 Replies View Related

Updating A Production Database With Back Up Of Development Database

May 11, 2007

Can someone provide a step by step tutorial for this? I'd like to safely update a database that is used for a website without much or any downtime.

View 1 Replies View Related

Updating Database From Dataset (Insert INTO)

Mar 2, 2007



Hello there

I have a code to update an access database from one of my dataset tables, but i want to insert columns manually

currently i am using this code to update my db

Dim cb As OleDb.OleDbCommandBuilder = New OleDb.OleDbCommandBuilder(dtadpt)

AccessConn.Open()

dtadpt.Update(DataSet, "recordsforupdate")

AccessConn.Close()

this code automatically inserts all the columns of dataset table to the access database table.

what i want is to inset the values for eg. in col4 of my dataset table into col5 of my access table, for that i want to manually use "inset into" statement to update the db table, but i am having problem with the syntax for using dataset..can anyone help please

thanks and bext regards

Saad

View 1 Replies View Related

Updating A Permanent Table From A Dataset Within The Data Flow

Feb 14, 2007

I have a dataset that was created via a source + lookups + derived columns.

I wish to take this dataset and treat is as a table within a sql statement so that I can update a permanent table with the a specific value within the temp dataset.

In sql this is what I am trying to do:

SELECT COUNT(*) AS Count_of_Employees, DEPT
FROM Employees
GROUP BY DEPT

UPDATE Departments
SET Number_of_Employees = Count_of_Employees
WHERE Dept = dept.

View 1 Replies View Related

Table Scans - More Rows Brought Back Than In Table

Jul 20, 2005

I have a query which is quite complex. It's based on a set of data ina complex view which takes the data from several tables.In this complex query, if I allow the various parts of the query towork on the results of the view (MISView), it can take 15 minutes torun (eek !), however, if I create a temporary table with the data fromthe view and then use that for the remainder of the query, it runs inapprox 20 seconds.Now, I have examined the execution plan (my new favourite toy) andthere is a difference (as expected). However when looking at the partof the query that takes up most of the time, it shows that it bringsback 109,645,866 records from a table (Credit) that contains 13,002records. This table is one that is referenced in the view (MISView)which contains 13,653 records and does get some of it's data from thetable which is scanned (Credit).For the record, we don't have any tables with over 100,000 records in,so 109 million rows is going some for us. The part of the query thatruns slow does reference another copy of itself but this is necessaryfor the equation that is being run.Now I'm OK with why it's doing the table scan, but why does it bringback substantially more data than is in the table ? Is it somemultiple of the number of records that it's trying to work out. Iassume it tries to run a seperate plan for the view as part of it'sprocess.Ideally, I'm still going to go down the route of the temporary table,but I would like to understand more about what it does first as Idon't like leaving things unanswered.Any help would be appreciated.

View 6 Replies View Related

Report Table Does Not Display All Rows From Dataset

Jan 12, 2007

I have a dataset that when run returns 270 rows. The table using the dataset in the report only prints the first row. I have the table grouped by a status type, but this is for when I can get multi-select paramenters installed and working. For now I just need the report to print all the returned rows. Help!!

Thanks!

Terry

View 1 Replies View Related

Insert Multiple Rows From Dataset Into SQL Database

Aug 16, 2006

Hi,
is there anyway to insert all the rows from a dataset to SQL Server table in a single stretch..

Thanks
Anz

View 1 Replies View Related

Updating Multiple Rows At Once In To SQlServer2005 Table

Sep 25, 2007

Hi,

I have a table called "tblProducts" with following fields:-

ProductID(Pk, AutoIncrement), ProductCode(FK), ProdDescr.

So to the above table I have added a new field/column named "ProdLongDescr(varchar, Null)"

So, I need to populate this newly added column with specific values for each row depending on "ProductCode" which is different forevery row. The problem is that I have 25 rows.So instead of Writing 25 individual update scripts, is there a way in which single query will do the same job instead of writing one update query for each row ?. If so can some one guide me how to achieve that OR point to me a good resource.

Below are a couple of Individual update scripts I Wrote. "ProductCode" is different for all 25 rows.

Update tblValAdPackageElement SET ProdLongDescr = 'Slideshows' WHERE ProductCode = 'SLID'
And szElementDescr='Slideshow'
if @@error <> 0
begin
goto ErrPos
end

Update tblValAdPackageElement SET ProdLongDescr = 'CategorySlideshows' WHERE ProductCode = 'SLDC'
And szElementDescr='CategorySlideshow'
if @@error <> 0
begin
goto ErrPos
end

Thanks,

View 1 Replies View Related

Updating A Column In A Table That Contains 50 Million Rows

Feb 27, 2008

I'm looking for some performance assistance on updating a column value in a table that contains approximately 50 million rows. I have a permanent table in another database that has the key column and value to be set. My query is listed below, but I'm afraid it will run quite awhile. Any suggestions would be appreciated.

update mytable
set column2 = b.column2
from mytable as a
join mytable1 as b
on a.column1 = b.column1



There is a one to one relationship between the two tables.

View 8 Replies View Related

Update A Dataset From An Updated MSSQL Table

May 23, 2007

Here is my problem: I've created a table in MSSQL named MyReferences and then a typed dataset to connect to it.



Then I realized that I needed to add a column to MyReferences table and then I did it.



The problem is that I cannot find a way to add the new column to the typed dataset. I am unable to view it in the available columns.



Can anyone help me?



I'm using Visual Studio 2005 sp1 and C#.



Best regards



Alessandro

View 1 Replies View Related

Updating Multiple Rows Based On Sums From Another Table

Apr 12, 2007

Hello All

I am trying to figure out if what i am attempting to do is possible and whether or not my approach is wrong to begin with.

I am trying to build a custom report for our accounting system which is Traverse from Open systems. This is what i have done in the stored procedure thus far


SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO

ALTER PROCEDURE rptArFLSalesByCustItemized_sp
@custId pCustID,
@dateFrom datetime,
@dateThru datetime,
@itemIdFrom pItemId,
@itemIdThru pItemId
as
set nocount on

-- define some variables for previous year
declare @LYqty int, @LyAmt money, @LYfrom datetime, @LYthru datetime

-- set defaults
SET @itemIdFrom=ISNULL(@itemIdFrom,(SELECT MIN(itemId) FROM tblInItem))
SET @itemIdThru=ISNULL(@itemIdThru,(SELECT MAX(itemId) FROM tblInItem))
SET @LYfrom=DATEADD(YEAR,-1,@dateFrom)
SET @LYthru=DATEADD(YEAR, -1, @dateThru)

-- create small temp table to hold customer info
Create Table #tmpArCustInfo
(
custId pCustID,
custName VARCHAR (30),
)
-- populate customer temp table with info
Insert into #tmpArCustInfo
select custId, custName
from tblArCust
WHERE custId = @custId


-- create a temp table to hold the Data for each Item
Create Table #tmpArSalesItemized
(
itemId pItemId,
productLine VARCHAR (12),
pLineDesc VARCHAR (35),
descr VARCHAR (35),
LYQtySold int,
LYTDQtySold int,
QtySold int,
LYTDsales money,
totalSales money,
LastInvDate datetime,
)

-- populate the temp table with all of the inventory items
insert into #tmpArSalesItemized
select ii.itemId, ii.productLine, ip.Descr, ii.Descr, 0,0,0,0,0, NULL
from tblInItem ii, tblInProductLine ip
where ip.productLine = ii.productLine
AND ii.itemId BETWEEN @itemIdFrom AND @itemIdThru

-- update table with this years quantities
update #tmpArSalesItemized
SET QtySold = (select SUM(QtyOrdSell) from tblArHistDetail hd
where TransId IN (select TransId from tblArHistHeader where custId = @custId)
AND orderDate IN (select OrderDate from tblArHistHeader where OrderDate BETWEEN @dateFrom AND @dateThru)
AND hd.partId BETWEEN @itemIdFrom AND @itemIdThru
GROUP BY hd.partId
)

-- Return the temp tables results
select * from #tmpArSalesItemized, #tmpArCustInfo

drop table #tmpArSalesItemized, #tmpArCustInfo

return


GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO


My problems begin where i want to start updating all of the Qty's of the QtySold field. I have managed to get it to write the same sum in every field but i cannot figure out how to update each row based on the sum of the qty found for that item in the tblArHistDetails table, trouble is too that there is no reference to the custId in that table either. The custId resides in tblArHistHeader and is linked to the details table via the TransId column. So really i need to update many rows based on criteria from 2 other tables.

Can anyone please help? I dont have a clue how to make this work, and most of what i have learned about sql thus far has been from opening other stored procs etc in the accounting system and just reading to see how the developers have done things.

Thanks
Jamie

View 1 Replies View Related

Integration Services :: Updating A Table With Billion Rows

Aug 5, 2014

It was an interview question, what's the best way to update a table with 10 billion rows.

View 16 Replies View Related

SQL Query - Updating Selected Rows/Creating New Row - Same Table

Jan 24, 2008

I have to write a couple scripts that will update a couple columns in two separate tables and also insert a new row with the same data except for a few calculated or provided values ...... see specs below ...




1. tGradeHist Table Script One (Needs to be run first)



a. Read tGradeHist Table and Select rows with GradeEndDate = NULL and GradeStartDate = '1/1/2007 12:00:00 A.M.'

b. Calculate New Step Amount = StepAmount * Incr% (Round To Nearest Whole Dollar)

c. Create New Row for this table using information from row read above and insert new information where indicated :


GradeCode - Same

GradeLocationCode - Same

Step - Same

GradeStartDate - '7/1/2007 12:00:00 A.M.'

GradeEndDate - NULL

GradeCurrencyCode - Same

StepAmount - Result of b (above)

GradeFrequencyCode - Same

RangeMaximumAmount - Same

RangeMidAmount - Same

RangeMinimumAmount - Same

GradeCurrentFlag - 'True'

MarketMaximumAmount - Same

MarketMidAmount - Same

MarketMinimumAmount - Same

GradeGUID - Same

TSCOL - Same


d. Update Row read in a (above) with GradeEndDate = '6/30/2007 12:00:00 A.M.' and GradeCurrentFlag = 'False'





2. tPersonBasePayHist Table Script Two (Needs to be run second)


a. Read tPersonBasePayHist Table and Select rows with PersonBasePayEndDate = NULL

b. Calculate New PersonBasePayAmount = PersonBasePayAmount * Incr% (Round To Nearest Whole Dollar)

c. Create New Row for this table using information from row read above and insert new information where indicated :



PersonGUID - Same

PersonBasePayStartDate - '7/1/2007 12:00:00 A.M.'

PersonBasePayEndDate - NULL

PersonBasePayCurrencyCode - Same

PersonBasePayAmount - Result of b (above)

PersonBasePayFrequency - Same

PersonBasePayPayrollFrequencyCode - Same

BasePayReasonCode - 'SA'

ConductedBasePayReviewDate - Same

ScheduledBasePayReviewDate - Same

PayrollCode - Same

PersonBasePayCurrentFlag - 'True'

ApprovedByPersonGUID - Same

PersonBasePayGUID - Same

TSCol - Same



d. Update Row read in a (above) with PersonBasePayEndDate = '6/30/2007 12:00:00 A.M.' and PersonBasePayCurrentFlag = 'False'














View 7 Replies View Related

Dataset Into A Table Or Matrix With Fixed Number Of Columns, Variable Rows

Jul 13, 2007

Hi

I have a dataset with 2 columns, a rownumber and a servername - eg



rownumber servername

1 server1

2 server2

....

15 server15



I want to display the servernames in a report so that you get 3 columns - eg



server1 | server2 | server3

server4 | server5 | server6

...

server13 | server14 | server15



I have tried using multiple tables and lists and filtering the data on each one but this then makes formating very hard - i either end up with a huge gap between columns or the columns overlap



I have also tried using a matrix control but cant find a way to do this.



Does anybody know an easy way to do this? The data comes from sql 2005 so i can use a pivot clause on the dataset if somebody knows a way to do it this way. The reporting service is also RS2005



Thanks



Anthony

View 1 Replies View Related

How Do I Update A SQLCE SDF Table With A Dataset Returned From A Webservice?

Jun 14, 2007

I have an existing call to a webservice that updates an MDB with data from a dataset.
I was now moving to a process using SQL Compact Edition sdf instead of an mdb.

I belive I have to DROP/Truncate the table in the SDF file, then create a new table then somehow insert the results of the retrieved dataset into the new table. DOes anybody have any pointers to help me out?

Here is my old way of doing it, using access.

Thanks.

Private Sub retrieveData(ByVal intMode As Integer)
'This process will call a webservice passing a parameter which in turn executes a SQL stored procedure, returning a dataset
Dim MyObj As localhost.Service1 = New localhost.Service1
Dim ds As DataSet
ds = MyObj.RetrieveSQLdata(txtSecureString, intMode)
Dim myConnection As OleDbConnection
Dim cmd As OleDbCommand = New OleDbCommand
Dim Connstr As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & Path & FileName & ";Persist Security Info=False"
myConnection = New OleDbConnection(Connstr)
myConnection.Open()
cmd.Connection = myConnection
Dim mystr As String = ""
For Each row As DataRow In ds.Tables(0).Rows
mystr = ""
mystr = mystr & "INSERT INTO CustMast ( "
mystr = mystr & "StoreNo, CustNo, ShipNo"
mystr = mystr & "values("
mystr = mystr & "'" & row("StoreNo").ToString & "', "
mystr = mystr & "'" & row("CustNo").ToString & "', "
mystr = mystr & "'" & row("ShipNo").ToString & "')"
cmd.CommandText = mystr
cmd.ExecuteNonQuery()
Next
System.Windows.Forms.Application.DoEvents()
cmd.Dispose()
myConnection.Close()
myConnection.Dispose()

End Sub

View 1 Replies View Related

Transact SQL :: Updating Table Rows With Overlapping Dates (extend)

Dec 2, 2015

This question is extension from the topic Updating table Rows with overlapping dates: [URL] .....

I am actually having a table as following:

Table Name: PromotionList

Note that the NULL in endDate means no end date or infinite end date.

ID PromotionID StartDate EndDate Flag
1 1 2015-04-05 2015-05-28 0
2 1 2015-04-23 NULL 0
3 2 2015-03-03 2015-05-04 0
4 1 2015-04-23 2015-05-29 0
5 1 2015-01-01 2015-02-02 0

And I would like to produce the following outcome to the same table (using update statement): As what you all observe, it merge all overlapping dates based on same promotion ID by taking the minimum start date and maximum end date. Only the first row of overlapping date is updated to the desired value and the flag value change to 1. For other overlapping value, it will be set to NULL and the flag becomes 2.

Flag = 1, success merge row. Flag = 2, fail row

ID PromotionID StartDate EndDate Flag
1 1 2015-04-05 NULL 1
2 1 NULL NULL 2
3 2 2015-03-03 2015-05-04 1
4 1 NULL NULL 2
5 1 2015-01-01 2015-02-02 1

The second part that I would like to acheive is based on the first table as well. However, this time I would like to merge the date which results in the minimum start date and End Date of the last overlapping rows. Since the End date of the last overlapping rows of promotion ID 1 is row with ID 4 with End Date 2015-05-29, the table will result as follow after update.

ID PromotionID StartDate EndDate Flag
1 1 2015-04-05 2015-05-29 1
2 1 NULL NULL 2
3 2 2015-03-03 2015-05-04 1
4 1 NULL NULL 2
5 1 2015-01-01 2015-02-02 1

Note that above is just sample Data. Actual data might contain thousands of records and hopefully it can be done in single update statement.

Extending from the above question, now two extra columns has been added to the table, which is ShouldDelete and PromotionCategoryID respectively.

Original table:

ID PromotionID StartDate EndDate Flag ShouldDelete PromotionCategoryID
1 1 2015-04-05 2015-05-28 0 Y 1
2 1 2015-04-23 2015-05-29 0 NULL NULL
3 2 2015-03-03 2015-05-04 0 N NULL
4 1 2015-04-23 NULL 0 Y 1
5 1 2015-01-01 2015-02-02 0 NULL NULL

Should Delete can take Y, N and NULL
PromotionCategoryID can take any integer and NULL

Now it should be partition according with promotionid, shoulddelete and promotioncategoryID (these 3 should be same).

By taking the min date and max date of the same group, the following table should be achieve after the table is updated.

Final outcome:

ID PromotionID StartDate EndDate Flag ShouldDelete PromotionCategoryID
1 1 2015-04-05 NULL 1 Y 1
2 1 2015-04-23 2015-05-29 1 NULL NULL
3 2 2015-03-03 2015-05-04 1 N NULL
4 1 NULL NULL 2 Y 1
5 1 2015-01-01 2015-02-02 1 NULL NULL

View 2 Replies View Related

~TableAdapter.Update Not Updating The Database

Apr 28, 2006

I am designing my first database (Visual Basic & SQL Server Express 2005) and it appears as if the database isn't updating. I am running it by hitting F5, closing by hitting the "X" and then hitting F5 again to check if the changes have stuck. They don't. These are the instructions given in the tutorial.

Any ideas? Thanks.

In particular I have tried two step-by-step tutorials distributed by Microsoft: 1. Absolute Beginner's Video Series, Lesson09; and 2. the Help tutorial: Managing Your Records (ms-help://MS.VSExpressCC.v80/MS.NETFramework.v20.en/dv_vbcnexpress/html/1ccdb8f1-4162-4a54-af17-231007eb529b.htm)

The code for the form is:

Public Class Form1


Private Sub AddressesBindingNavigatorSaveItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AddressesBindingNavigatorSaveItem.Click


Me.Validate()

Me.AddressesBindingSource.EndEdit()

Me.AddressesTableAdapter.Update(Me.FirstDatabaseDataSet.Addresses)

End Sub

Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing


Me.AddressesBindingSource.EndEdit()

Me.AddressesTableAdapter.Update(Me.FirstDatabaseDataSet.Addresses)

End Sub

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load


'TODO: This line of code loads data into the 'FirstDatabaseDataSet.Addresses' table. You can move, or remove it, as needed.

Me.AddressesTableAdapter.Fill(Me.FirstDatabaseDataSet.Addresses)

End Sub
End Class

View 3 Replies View Related

Saving A Custom Object In A Sql Database Table.

Dec 6, 2005

Hi,Using VB.net I have created a custom object (hope my terminology is correct here), it’s just a class that defines a few string, integer, and hash table variables. After creating an instance of this class and populating it with data I need to be able to store this instance of my object in a sql server data base table. How do I do this? I saw an article that used the image data type to achieve this (code was in java unfortunately) is this the correct approach. Could you please give me some code examples
Thanks

View 1 Replies View Related

Dataset.Tables.Count=0 Where There Are 2 Rows In The Dataset.

May 7, 2008

Hi,
I have a stored procedure attached below. It returns 2 rows in the SQL Management studio when I execute MyStorProc 0,28. But in my program which uses ADOHelper, it returns a dataset with tables.count=0.
if I comment out the line --If @Status = 0 then it returns the rows. Obviously it does not stop in
if @Status=0 even if I pass @status=0. What am I doing wrong?
Any help is appreciated.


ALTER PROCEDURE [dbo].[MyStorProc]

(

@Status smallint,

@RowCount int = NULL,

@FacilityId numeric(10,0) = NULL,

@QueueID numeric (10,0)= NULL,

@VendorId numeric(10, 0) = NULL

)

AS

SET NOCOUNT ON

SET CONCAT_NULL_YIELDS_NULL OFF



If @Status = 0

BEGIN

SELECT ......
END
If @Status = 1
BEGIN
SELECT......
END



View 4 Replies View Related

Write DataSet Back To SQL

Sep 10, 2004

Hello everybody,
I have a dataset that i read from an xml file.
I need to import this database back in to sql..
Is there a easy way.. Or do i need to loop thorugh each record in the dataset to import it.

Thanks

Chris

View 2 Replies View Related

Custom Task Not Updating Property Values Or Saving.

May 2, 2008

Hi Folks,

I have a task I wrote which does not always update the property value (as seen in the properties pane)
Basically, change something on the form, then update the task host property with:
this.taskHostValue.Properties["Duration"].SetValue(this.taskHostValue, Convert.ToInt32(spnDuration.Value));

Stepping through this, it does exactly what it is supposed to. Having a look at the property value, it confirms it has changed.
Reopening the UI and resetting all the controls returns the expected results.

The package however does not realise it has changed. There is no * next to the package name in the top tabs.
As long as the package thinks it is unchanged, SaveXML does not get called either so the tasks do not persist.

Changing the value on the properties pane works fine though.

The frustrating thing is this is slightly random. Slight in the sense that sometimes it works but most of the time it does not.


The sample code I used was the MS download IncrementTask (Which works BTW) so I can't see it as being a VS / SSIS bug but rather something I am / am not doing. 3 tasks I have written all behave the same. I have to "nudge" them before savign the package.

Any ideas what the problem might be?



TIA


Cheers,
Crispin

View 3 Replies View Related

Pull Back Data Using A Dataset

Feb 19, 2008

Hello, I am trying to pull run this sql statement but it's bombing out at the comm.ExecuteNonQuery();. ..
 
Could someone help me figure this out..
 Ex.System.Int32 bum = System.Convert.ToInt32(Request.QueryString["dum"]);
SqlConnection conn = new SqlConnection("Data Source=**********************");SqlCommand comm = new SqlCommand();
comm.Connection = conn;SqlDataAdapter myadapter = new SqlDataAdapter(comm);DataSet myset = new DataSet();
conn.Open();
 comm.CommandText = "Select * from Order_Forms where (Order_Num = " + Session["dum1"] + " ) ";
 
comm.ExecuteNonQuery();myadapter.Fill(myset, "Order_Forms");
myset.AcceptChanges();
 
Can yo usee the problem???
 
 
 

View 7 Replies View Related

Tables Not Being Written Back To DB From Dataset. I'm Going Nutz!

Sep 26, 2006

ok. the problem: some tables are empty, so i can't be sure why some are updating at the DB and some arent.
I have manually picked thru every line of the xml that i'm reading into the dataset here, and it is fine, data is all valid and everything.
the tables i'm most worried about are bulletins and surveys, but they all have to be imported from my upload, the code steps thru just fine and I've been thru it a million times. Did I miss something in my dataadapter configuration?. 'daBulletin        '        Me.daBulletin.ContinueUpdateOnError = True        Me.daBulletin.DeleteCommand = Me.SqlDeleteCommand17        Me.daBulletin.InsertCommand = Me.SqlInsertCommand17        Me.daBulletin.SelectCommand = Me.SqlSelectCommand25        Me.daBulletin.TableMappings.AddRange(New System.Data.Common.DataTableMapping() {New System.Data.Common.DataTableMapping("Table", "tblBulletin", New System.Data.Common.DataColumnMapping() {New System.Data.Common.DataColumnMapping("BulletinID", "BulletinID"), New System.Data.Common.DataColumnMapping("ContractID", "ContractID"), New System.Data.Common.DataColumnMapping("Msg_Type", "Msg_Type"), New System.Data.Common.DataColumnMapping("DatePosted", "DatePosted"), New System.Data.Common.DataColumnMapping("Subject", "Subject"), New System.Data.Common.DataColumnMapping("B_Body", "B_Body"), New System.Data.Common.DataColumnMapping("I_Read_It", "I_Read_It"), New System.Data.Common.DataColumnMapping("DateRead", "DateRead")})})        Me.daBulletin.UpdateCommand = Me.SqlUpdateCommand16
  here is my merge function: Private Function Merge(ByVal sFilename As String, ByVal User As String) As String
        Dim connMerge As New SqlConnection(ConnectionString)
        Dim dsNew As New dsBeetleTracks
        Dim dsExisting As New dsBeetleTracks
        Dim strResult As String
        SetConnections(connMerge)
        Dim idc As New System.Security.Principal.GenericIdentity(User)
        Dim currentUser As BeetleUser = bu

        dsNew.ReadXml(sFilename)

        If currentUser.IsInRole("Admin") Or currentUser.IsInRole("QA") Then
            If dsNew.tblBulletin.Count > 0 Then
                daBulletin.Fill(dsExisting.tblBulletin)
                dsExisting.Merge(dsNew.tblBulletin)
                strResult += daHelipads.Update(dsExisting.tblBulletin).ToString + " Bulletins updated<br>"
            End If
        End If

        If dsNew.tblHours.Count > 0 And (currentUser.IsInRole("Survey") Or currentUser.IsInRole("Admin")) Then
            daHours.Fill(dsExisting.tblHours)
            dsExisting.Merge(dsNew.tblHours)

            strResult += daHours.Update(dsExisting.tblHours).ToString + " hours updated<br>"
        End If

        If dsNew.tblHeliPads.Count > 0 Then
            daHelipads.Fill(dsExisting.tblHeliPads)
            dsExisting.Merge(dsNew.tblHeliPads)
            strResult += daHelipads.Update(dsExisting.tblHeliPads).ToString & " helipads updated "
        End If

        If dsNew.tblExpenses.Count > 0 Then
            daExpenses.Fill(dsExisting.tblExpenses)
            dsExisting.Merge(dsNew.tblExpenses)

            strResult += daExpenses.Update(dsExisting.tblExpenses).ToString + " expenses updated<br>"
        End If

        If dsNew.tblPersons.Count > 0 And (currentUser.IsInRole("Survey") Or currentUser.IsInRole("FB") Or currentUser.IsInRole("Heli-burn")) Then
            daPersons.Fill(dsExisting.tblPersons)
            dsExisting.Merge(dsNew.tblPersons)
            strResult += daPersons.Update(dsExisting.tblPersons).ToString + " persons updated<br>"
        End If

        If currentUser.IsInRole("Field") Then
            daSurveys.SelectCommand.CommandText = "exec Surveys_Field_Select"
            daSurveys.InsertCommand.CommandText = "exec Surveys_Field_Insert"
            daSurveys.UpdateCommand.CommandText = "exec Surveys_Field_Update"
        End If

        If dsNew.tblSurveys.Count > 0 And (currentUser.IsInRole("Survey") Or currentUser.IsInRole("Field")) Then ' Or CurrentUser.IsInRole("Admin")) Then

            daSurveys.Fill(dsExisting.tblSurveys)
            dsExisting.Merge(dsNew.tblSurveys)

            strResult += daSurveys.Update(dsExisting.tblSurveys).ToString + " surveys updated<br>"
        End If

        If dsNew.tblSurveyChecks.Count > 0 And (currentUser.IsInRole("QA") Or currentUser.IsInRole("Admin")) Then
            daSurveyChecks.Fill(dsExisting.tblSurveyChecks)
            dsExisting.Merge(dsNew.tblSurveyChecks)

            strResult += daSurveyChecks.Update(dsExisting.tblSurveyChecks).ToString + " survey checks updated<br>"
        End If

        If dsNew.tblTreatments.Count > 0 And (currentUser.IsInRole("FB") Or currentUser.IsInRole("Heli-burn")) Then ' Or CurrentUser.IsInRole("Admin")) Then
            daTreatments.Fill(dsExisting.tblTreatments)
            dsExisting.Merge(dsNew.tblTreatments)

            strResult += daTreatments.Update(dsExisting.tblTreatments).ToString + " treatments updated<br>"
        End If

        If dsNew.tblInternalQC.Count > 0 And (currentUser.IsInRole("FB") Or currentUser.IsInRole("Heli-burn") Or currentUser.IsInRole("Survey")) Then ' Or CurrentUser.IsInRole("Admin")) Then
            daInternalQC.Fill(dsExisting.tblInternalQC)
            dsExisting.Merge(dsNew.tblInternalQC)

            strResult += daInternalQC.Update(dsExisting.tblInternalQC).ToString + " internalqc updated<br>"
        End If

        If dsNew.tblTreatmentChecks.Count > 0 And (currentUser.IsInRole("QA") Or currentUser.IsInRole("Admin")) Then
            Try
                daTreatmentChecks.Fill(dsExisting.tblTreatmentChecks)
                dsExisting.Merge(dsNew.tblTreatmentChecks)
                strResult += daTreatmentChecks.Update(dsExisting.tblTreatmentChecks).ToString + " treatment checks updated<br>"
            Catch dbex As DBConcurrencyException
                strResult += vbCrLf & dbex.Message
                For x As Integer = 0 To dbex.Row.Table.Columns.Count - 1
                    strResult += vbCrLf & dbex.Row.GetColumnError(x)
                Next
            End Try
        End If

        If dsNew.tblHeliPiles.Count > 0 And (currentUser.IsInRole("Heli-burn")) Then ' Or CurrentUser.IsInRole("Planner")CurrentUser.IsInRole("QA") Or CurrentUser.IsInRole("Admin") Or
            daHeliPiles.Fill(dsExisting.tblHeliPiles)
            dsExisting.Merge(dsNew.tblHeliPiles)

            strResult += daHeliPiles.Update(dsExisting.tblHeliPiles).ToString + " piles updated<br>"
        End If

        If dsNew.tblHeliCycles.Count > 0 And (currentUser.IsInRole("Heli-burn")) Then ' CurrentUser.IsInRole("Planner") Or Or CurrentUser.IsInRole("Admin")) Then
            daHeliCycles.Fill(dsExisting.tblHeliCycles)
            dsExisting.Merge(dsNew.tblHeliCycles)

            strResult += daHeliCycles.Update(dsExisting.tblHeliCycles).ToString + " cycles updated<br>"
        End If

        If dsNew.tblHeliTurns.Count > 0 And (currentUser.IsInRole("Heli-burn")) Then 'CurrentUser.IsInRole("Admin") Or CurrentUser.IsInRole("Planner") Or
            daHeliTurns.Fill(dsExisting.tblHeliTurns)
            dsExisting.Merge(dsNew.tblHeliTurns)

            strResult += daHeliTurns.Update(dsExisting.tblHeliTurns).ToString + " turns updated<br>"
        End If

        If dsExisting.HasChanges Then
            dsExisting.Merge(dsNew)
        End If
        dsExisting.AcceptChanges()


        'duh.
        'If dsNew.HasChanges Then
        '    dsNew.AcceptChanges()
        'End If
        If dsExisting.HasErrors Then
            Dim bolError As Boolean
            Dim tempDataTable As DataTable
            bolError = True

            strResult += "<br>"

            For Each tempDataTable In dsExisting.Tables
                If (tempDataTable.HasErrors) Then
                    strResult += PrintRowErrs(tempDataTable)
                End If
            Next
        End If

        dsNew.Dispose()
        dsExisting.Dispose()
        connMerge.Close()
        'edebugging will only track strresult
        Dim fsError As New FileStream(Server.MapPath("./incoming/error.txt"), FileMode.Create, FileAccess.Write)
        Dim swError As New StreamWriter(fsError)
        swError.WriteLine("--==ERROR LOG==--")
        swError.WriteLine(Now.Date.ToShortDateString)
        swError.WriteLine("-----------------")
        swError.WriteLine(strResult)
        swError.Close()
        fsError.Close()

        Return strResult
    End Function

View 2 Replies View Related

Stored Procedure That Fetch Each Row Of A Table And Update Rows In Another Table

Jan 31, 2006

I am working with the following two tables:

Category(NewID,OldID)
Link(CategoryID,BusinessID)

All fields are of Integer Type.

I need to write a stored procedure in sql 2000 which works as follows:

Select all the NewID and OldID from the Category Table
(SELECT NewID,OldID FROM Category)

Then for each rows fetched from last query, execute a update query in the Link table.

For Example,

Let @NID be the NewID for each rows and @OID be the OldID for each rows.
Then the query for each row should be..

UPDATE Link SET CategoryID=@CID WHERE CategoryID=@OID

Please help me with the code.

Thanks,
anisysnet

View 1 Replies View Related

SQL Server 2012 :: Update Statement Will Not Update Data Beyond 7 Million Plus Rows Out Of 38 Millions Rows

Dec 12, 2014

I run the following statement and it will not update beyond 7 million plus rows and I have about 38 million to complete. I keep checking updated row counts and after 1/2 day it's still the same so I know something is wrong because it was rolling through no problem when I initiated it. I need to complete ASAP so it's adding to my frustration. The 'Acct_Num_CH' field is an encrypted field (fyi).

SET rowcount 10000
UPDATE [dbo].[CC_Info_T]
SET [Acct_Num_CH] = 'ayIWt6C8sgimC6t61EJ9d8BB3+bfIZ8v'
WHERE [Acct_Num_CH] IS NOT NULL
WHILE @@ROWCOUNT > 0
BEGIN
SET rowcount 10000
UPDATE [dbo].[CC_Info_T]
SET [Acct_Num_CH] = 'ayIWt6C8sgimC6t61EJ9d8BB3+bfIZ8v'
WHERE [Acct_Num_CH] IS NOT NULL
END
SET rowcount 0

View 5 Replies View Related

Database Automatically Creates Xxx_Temp Table While Modifying / Updating Table Structure .

Dec 16, 2007

Hello friends,

I am new to the SQL Server 2005 development.

From last 1 week or so, i have been facing very strange problem with my sql server 2005s database
which is configured and set on the hosting web server. Right now for managing my sql server 2005 database,
i am using an web based Control Panel developed by my hosting company.

Problem i am facing is that, whenever i try to modify (i.e. add new columns) tables in the database,
it gives me error saying that,

"There is already an object named 'PK_xxx_Temp' in the database. Could not create constraint. See previous errors.
Source: .Net SqlClient Data Provider".

where xxx is the table name.

I have done quite a bit research on the problem and have also searched on the net for solution but still
the problem persist.

Thanks in advance. Any help will be appreciated.

View 5 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved