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");
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();
Hello,I am trying to update the Image type field named as BlobData in sqlServer 2000. I capture the record in a data set to have the schema and try to update the BlobData field of type Image by assigning it a value of buffer as below. but my assignment seems to be wrong and generates an error saying Object reference not set. Code========================= Dim fileBuffer(contentLength) As Byte
Dim attachmentFile As HttpPostedFile = Me.fileUpload_fu.PostedFile
Catch ex As Exception Me.error_lbl.Text = ex.Message Return False Finally cn.Close() End Try ========================== Can anyone please help this one out. Cheers.Imran.
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
I need to update about 1.3 million rows in a table of mine. I am getting the data from one of the columns of the same table and updating the new column. I am doing this using a cursor which I have put in a stored procedure. As this is a production table which users might be accessing.It is a web based application and I can't slow the system down. So I am willing to run the stored prcedure during off peak hours. However, do I need to put this in a transaction? If I did put it in a transaction what type of isolation level should I opt for? Data integrity is very important for me and I don't mind to compromise on the performance. I am doing this because one of the columns which has "short description" entry is has become too small for business purposes and we want to increase it's length from varchar(100) to varchar(150). As this is SQL 6.5, I can't increase the lenght of the column. So Iadded a new column and will run the stored proc. What precautions are to be taken? This is on a high priority basis and very important too.
Thanks in advance...
Stored procedure code:
USE DB_Registration_Dev GO IF EXISTS (SELECT NAME FROM SYSOBJECTS WHERE NAME='usp_update_product' AND TYPE='P') DROP PROCEDURE usp_update_product GO CREATE PROC usp_update_product AS DECLARE @short_desc varchar(100) DECLARE @prod_id int
DECLARE sdesc_curs CURSOR FOR SELECT [Product].[product_id] , [Product].[short_description] FROM Product
OPEN sdesc_curs
FETCH NEXT FROM sdesc_curs INTO @prod_id, @short_desc
WHILE @@FETCH_STATUS = 0 BEGIN UPDATE Product SET [Product].[sdesc] = @short_desc WHERE Product_id=@prod_id FETCH NEXT FROM sdesc_curs INTO @prod_id, @short_desc IF @@FETCH_STATUS <> 0 PRINT ' Finished Updating the table...go ahead and have fun ...! ' END DEALLOCATE sdesc_curs GO
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.
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.
Hi all, I'm trying to update various rows in my DB with a new value once an action occurs. I am using the following code which does not throw any exceptions, but also does not change the values. Can someone steer me in the right direction? public static void ChangeRefCode() { SqlConnection dbConn = new SqlConnection(ConnectDB.getConnectString()); SqlDataAdapter dataAdapt = new SqlDataAdapter("Select * from Posting",dbConn);
Hi,Ive got a class in my code which contains data from several tables. A user profile has a single record in a user_profile tables, for each of these records there is several records in a another table, which itself has several records in a tags table.So far the save method on the class saves the record to the user profile table, then loops through the next two tables info to insert each record. I want to decrease the number of trips to the database and am wondering if anyone can advise on the best way to do this.I am considering using a dataset to retrieve and store the records, instead of a datareader Im using currently. Then when Im done altering the data in the dataset (all three tables) I can commit all the changes in one database transaction?? I have been avoiding datasets due to the fact datareaders are apparently faster.My other option is to try make three calls to the database, one per table, updating my stored procedures to accept arrays of data using XML?? Can anyone tell me what is the best option for me?Thanks,C
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
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.
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);
Hello Team i want to insert more than one row to the dataset before update the sqladapter for ex i want to insert rows for orderlines then i send them all to sql by updating adapter is it done by javascript ? because when i press the button a postback hapend then it clears the dataset so the new row clears the old one any idea Thanks lot
I have a report with multiple datasets, the first of which pulls in data based on user entered parameters (sales date range and property use codes). Dataset1 pulls property id's and other sales data from a table (2014_COST) based on the user's parameters. I have set up another table (AUDITS) that I would like to use in dataset6. This table has 3 columns (Property ID's, Sales Price and Sales Date). I would like for dataset6 to pull the Property ID's that are NOT contained in the results from dataset1. In other words, I'd like the results of dataset6 to show me the property id's that are contained in the AUDITS table but which are not being pulled into dataset1. Both tables are in the same database.
I'm getting a strange error in SSRS when there is no data returned from a OLEDB datasource.
Here are the steps to simulate the error
1. Create 2 shared datasources to the Adventure Database - one using ADO MD provider (Microsoft SQL Server Analysis Services (AdomdClient)) and another using OLEDB (OLEDB 9.0 for Analysis Services)
2. Create a new report and create a dataset with the ADO-MD provider and copy and paste the below query. (This query will not return any data)
SELECT NON EMPTY [Measures].[End of Day Rate] ON 0 ,NON EMPTY {[Date].[Date].&[10000]} ON 1 FROM [Adventure Works]
3. Run report. It will be blank as nothing is defined in the layout. But this shows that the query is executed in the dataset and is succesfull although the query does not return any data.
4. Create another report and create a dataset with the OLE-DB provider and copy paste the above query.
5. Run the report. It will come back with error in the lines of "Object reference not set to an instance of an object". The reporting services log file will show that the query execution has failed although this is not the case when analysed from profiler.
Any ideas on how to solve this? What I'm trying to acheive is to use the NoRows property of table to display a message when there is no data. But I'm not able to pass the above hurdle when no data is returned from the dataset.
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!!
How would I update a table where id = a list of ids?Do I need to parse the string idList? I am being passed a comma seperated string of int values from a flex application.example: 1,4,7,8 Any help much appreciatedBarry 1 [WebMethod] 2 public int updateFirstName(String toUpdate, String idList) 3 { 4 SqlConnection con = new SqlConnection(connString); 5 6 try 7 { 8 con.Open(); 9 SqlCommand cmd = new SqlCommand(); 10 cmd.Connection = con; 11 cmd.CommandText = "UPDATE tb_staff SET firstName = @firstName, WHERE id = @listOfIDs"; 12 13 14 15 SqlParameter firstName = new SqlParameter("@firstName", toUpdate); 16 SqlParameter listOfIDs= new SqlParameter("@listOfIDs", idList); 17 18 19 20 cmd.Parameters.Add(firstName); 21 cmd.Parameters.Add(listOfIDs); 22 23 int i = cmd.ExecuteNonQuery(); 24 con.Close(); 25 return 1; 26 27 } 28 catch 29 { 30 return 0; 31 } 32 } 33 34
I am working on a SQL Server table designed by a partner company and cannot change the data structures. There is a table with a list of people available for calling out to a security system (keyholders).
From a web form, I need to allow my users to change the telephone calling order of the keyholders in the table.
The two important fields are AccountCode nVarChar and CallOrder nVarChar - where AccountCode + CallOrder must be unique.
As an example, the table may contain records with the following data..
1234, 1, Fred 1234, 2, Bert 1234, 3, Bob
If the user wants to make Bob the number 1 keyholder, Fred number 2 and Bert number 3 - what is the best practice for me to approach the update ?
Does anybody have a sample SQL script that will select table A and compare it to table B. If a row exists in both table A and table B, it will update the columns in table B with the columns in table A. If the row does not exist in table B, it will insert a row in table B using the row in table A. Is this possible?
I am new here, and I am sure this is a simple query, but im being forcefed database chores from my job, so i have to teach this stuff to myself/get help from places like this, I need help with a query, lets say that there are columns a,b,c,d,e,f,g if columns c,d,e are the same, than I want the info in column g changed to the info in column b in the first record of that group the reason I am doing this is, I have like items (sku's) grouped in my database, and i want to create a blanket part number for skus that have matching descriptions which is the information in colums c,d,e, I want to link them to the part number of the first product with that description, and add that part number in a new column at the end of the grouped SKU's record
this is what i start out with
a b c d e f g 2 4 5 6 9 8 2 5 5 6 9 9 2 7 5 6 0 5 1 2 3 4 5 6 1 3 3 4 5 7 1 4 3 4 5 8 1 5 3 4 5 9
i want to end up with a b c d e f g 2 4 5 6 9 8 4 2 5 5 6 9 9 4 2 7 5 6 0 5 7 1 2 3 4 5 6 2 1 3 3 4 5 7 2 1 4 3 4 5 8 2 1 5 3 4 5 9 2
I have put this thread on as a follow up discussion to some concepts that surfaced here:http://www.dbforums.com/showthread.php?t=1208316here:http://www.dbforums.com/showthread.php?t=1604936and also here:http://www.dbforums.com/showthread.php?t=1606555 The gist is: Is it ever correct excusable advisable to pass a non-normalised csv list of data to a stored procedure? When I first asked this I thought it was simply an implementation issue. Pat thinks it is but he also holds an ideological objection too. If I seem a little obsessed with this topic it is simply thata) I don't want to hijack yet another threadb) I am Anyway - I PMed Pat about this and he (quite rightly) suggested I post publicly. So here we go: I think I have struggled a little getting my head round the concepts you are using. And here (I think) is why: Normalisation starts with a logical model and ends with the physical implementation of the database (as I see it...). Relational theory pervades these two but extends further to SQL and database objects (views, sprocs etc). I work exclusively (with the exception of some legacy I stuff I simply must update) with the sproc database-API methodology. As such, my databases are abstracted from the other tiers. Now - I think this is the crux of it for me - I typically think of the sproc API as another tier (perhaps tier 1.5). Although the database itself and the objects that manipulate it are housed by a single application I don't actually think of the sprocs as part of the database. They are dependant upon it and inextricably intertwined with it but they are not a part of it in my eyes. As such, I don't worry about producing denormalised output and I have never (up until you got me thinking about it) worried about accepting non-normalised input. The sproc is not the database. The sproc is just a code procedure that acts upon the database. As such - if it accepts a typless, denormalised input but subsequently types (validates) it and normalises it before it makes any changes to the data within the database then I struggle to see the scale of the problem. I am writing as something of a stickler for normalisation myself - I think that rather than querying how closely one should adhere to normalisation principles I am pondering at what point these principles come into play. As a follow up question - if SQL Server sprocs were to accept (for example) a table variable as an argument would this meet your requirement (since the data is verified and normalised before it gets to the sproc) or would you require a solution like this to be an ANSI Standard too? So - that's the nub of it - comments welcome ona) The practicality of passing csv lists to sprocs and subsequently parsing them and b) How "correct" or "incorrect" this is. Blindman and Pat both object on both counts (I think).Thrasmachus didn't have a problem with it (however to be fair that was a very early response to a specific question I asked). I don't hold a particularly strong opinion either way – in fact the “loop through the changes at the client and fire the sproc n times” route is probably much easier to code in any case - I'm just interested in the idea that it violates relational theory in some way.
Hi, I need to update column week14 in table PastWeeks with data from Eng_Goal and then result of some calculation from table AverageEngTime in the row Goal and Used respectively. I used the following and was not successful. Please advice. Thank you.
Hi,New to writing sql scriptI get this error in my sql scriptServer: Msg 512, Level 16, State 1, Line 1Subquery returned more than 1 value. This is not permitted when thesubquery follows =, !=, <, <= , >, >= or when the subquery is used asan expression.The statement has been terminated.I want to write a single sql script which will update column 1 (FK)in table A with column 1 (PK) in table BHere's an example of what I need to doTable DATA_A-------------column C1 (Foreign Key)111111222222333333334455Table DATA_B------------column C1 (Primary Key) Column C2 Column C311 ABC NULL12 ABC 2004-12-1222 EFG NULL23 EFG 2003-12-1233 HIJ NULL34 HIJ 2003-12-1244 KLM 2005-02-0255 JJJ NULLI need to update Table DATA_A set column C1 with 11 data to point toTable DATA_B column C1 with 12 data. Currently, the problem is theTable DATA_A Column C1 is pointing to the wrong primary key which hasNULL data in COLUMN C3. I need to point to the correct Primary Key withDate filled in Column 3. The two primary key is tied together bycolumn C3.Here's my SQl scriptUPDATE DATA_A SET C1 =(SELECT C1 FROM DATA_BWHERE C2 in(SELECT B1.C2 FROM DATA_B B1WHERE EXISTS(SELECT * FROM TABLE_B B2 WHERE B2.C3 is NOT NULL)AND EXISTS(SELECT * from TABLE_B B2 WHERE B2.C3 is NULL)AND B2.C2 = B1.C2GROUP BY B1.C2HAVING COUNT(B1.C2) = 2)AND C3 IS NOT NULL)WHERE(SELECT C1 FROM DATA_BWHERE C2 in(SELECT B1.C2 FROM DATA_B B1WHERE EXISTS(SELECT * FROM TABLE_B B2 WHERE B2.C3 is NOT NULL)AND EXISTS(SELECT * from TABLE_B B2 WHERE B2.C3 is NULL)AND B2.C2 = B1.C2GROUP BY B1.C2HAVING COUNT(B1.C2) = 2)AND C3 IS NULL)Thanks - Been struggle at this for a whileMLR
Hi, I am preparing a project that contains multiple tables, because of huge operations to be performed, so i split these into two forms. I used one form for "Inserting Data in the multiple tables" and another form used for "Updating and Deleting Data from the multiple tables". I used a common identification number in all the tables are "License_Number" for inserting, retreving, updating and deleting the data. I used tabcontrol to place lot of controls on it.
The form-1 which is used for Inserting, works fine. The problem occuring in the second form which i used for updating.
The following code fill the data into the Textboxes and as well as in the datagridview. Below two tables "SetBack_Details" and "Far_Details" are fill the data in datagridview.
Private Sub FillDataFromAllTables(ByVal LicenseNumber As Long)
Try 'Fill Owner Personal Details Data CheckOwnerID = RetrieveOwnerIDFromPD(LicenseNumber) Me.Owner_Personal_DetailsTableAdapter.Fill(Me.LicenseFARModifyDataSet.Owner_Personal_Details, CheckOwnerID)
'------------------------------------------------------------------- 'Fill Project Details Data Me.ProjectDetailsTableAdapter.Fill(Me.LicenseFARModifyDataSet.ProjectDetails, LicenseNumber)
'------------------------------------------------------------------- 'Fill Consultant Details Data Me.Consultant_DetailsTableAdapter.Fill(Me.LicenseFARModifyDataSet.Consultant_Details, LicenseNumber) 'Fill Applicant Details Data Me.Applicant_DetailsTableAdapter.Fill(Me.LicenseFARModifyDataSet.Applicant_Details, LicenseNumber) '------------------------------------------------------------------- 'Fill Property Details Data Me.Property_DetailsTableAdapter.Fill(Me.LicenseFARModifyDataSet.Property_Details, LicenseNumber) '------------------------------------------------------------------- Me.SetBack_DetailsTableAdapter.Fill(Me.LicenseFARModifyDataSet.SetBack_Details, LicenseNumber) '------------------------------------------------------------------- Me.FAR_DetailsTableAdapter.Fill(Me.LicenseFARModifyDataSet.FAR_Details, LicenseNumber) Catch ex As Exception MessageBox.Show(ex.Message.ToString, "Project Details") End Try End
The data which i retrieves in a single record easily updated but problem occurs in DataGridView.
The data which binds to textboxes is easily updating because of a single record. Example is below UPDATE PROJECTdETAILS SET PNAME=@PNAME, ZONE=@ZONE, ZONEAREA=@ZONEAREA WHERE LicenseNumber=@LicenseNumber
The data which binds to datagridview is problem. I know the following statement is not appropriate to update the data rows in datagridview. UPDATE SETBACK_DETAILS SET DIRECTION=@DIRECTION, BORDERS=@BORDERS, DIMENSION=@DIMENSION WHERE LICENSENUMBER=@LICENSENUMBER What happening to the above statement is , all rows with this LICENSENUMBER contains same data. Before updating data contains in different information but after updating which ever last row is updating, it contains the last row values to all records.
Example : 101 xyzcompany X-Road X-Area 101 xyzcompany X-Road X-Area 101 xyzcompany X-Road X-Area 101 xyzcompany X-Road X-Area 101 xyzcompany X-Road X-Area . . The following code i used to save the data Private Sub SaveData() Me.ValidateChildren() Me.ProjectDetailsBindingSource.EndEdit() 'EndEdit for Project Details Me.Consultant_DetailsBindingSource.EndEdit() 'EndEdit for Consultant Details Me.Applicant_DetailsBindingSource.EndEdit() 'EndEdit for Applicant Details Me.Property_DetailsBindingSource.EndEdit() 'EndEdit for Property Details 'Me.SetBack_DetailsBindingSource.EndEdit() 'Endedit for SetBack_Details
Me.ProjectDetailsTableAdapter.Update(Me.LicenseFARModifyDataSet.ProjectDetails) 'Update Project Details Me.Consultant_DetailsTableAdapter.Update(Me.LicenseFARModifyDataSet.Consultant_Details) 'Update Consultant Details Me.Applicant_DetailsTableAdapter.Update(Me.LicenseFARModifyDataSet.Applicant_Details) 'Update Applicant Details Me.Property_DetailsTableAdapter.Update(Me.LicenseFARModifyDataSet.Property_Details) 'Me.SetBack_DetailsTableAdapter.Update(Me.LicenseFARModifyDataSet.SetBack_Details) End Sub
Please help me in the regard how to update the data in DataGridView which contains multiple recrods with different information for a single LicenseNumber. I try so many times with different sort of techniques but i fails, sometimes i get concurrency violation error and many more. Hope anybody understand my problem. Please help me in this regard.
Ok, I've spent a good amount on time on debugging an unupdating scenario in my application. Finally I knew the reason which is very annoying. Either I'm missing something really obvious (I hope so,) or this is a bug.
to reproduce what I'm talking about: 1- create a new win forms application using VS2005 sp1 2- add some SQL Compact Edition data file that have some records from the data menu, you'll get the designer to generate the dataset and everything.. 3- drag a table from the data sources window, you'll get the data grid and the navigator on the form 4- add a button and have this in the click event handler: datasetname.Clear(); TableAdapterName.Update(datasetname);
launch the program, click the button, you'll see the grid get wiped out as it supposed to do. close the program and relaunch. the data is there again (this has nothing to do with the copy always, copy if newer infamous stupidity)
now: 5- edit the click event handler and change it so something like this: foreach (datasetname.TableRow row in datasetname.Table) { row.Delete(); } TableAdapterName.Update(datasetname);
Launch the program, hit the button, grid wiped out. exit and relaunch. You'll see no data (i.e. the update on table adapter worked alright)
You can also try the GetChanges method on the dataset rightafter you use the clear method and you'd get no deleted records at all.
So, in 100,000+ records dataset, if i need to wipe the thing out and add some new records do i have to loop over every record and call delete (which will take LOTS of time). I do hope that I'm missing something obvious.
I need to update a empty column in our SQL database with the login ID for employees of our company.The table is called SY01200 and were I need to put the login ID is column INET5, and the login ID is just me stripping off the company's email address(removing the @company.com), and I need to update the INET5 column only where Master_Type = 'EMP'
And here is the Query that I am using to strip the email select LEFT(convert(varchar(40),EmailToAddress),LEN(convert(varchar(40),EmailToAddress))-14) As LoginName from sy01200 where Master_Type = 'emp'And here is what I thought the Query would be to update however I got and error saying more than 1 arguement returned
UPDATE sy01200 SET INET5 = (select LEFT(convert(varchar(40),EmailToAddress),LEN(convert(varchar(40),EmailToAddress))-14) As LoginName from sy01200 where Master_Type = 'emp') WHERE Master_Type = 'EMP'
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
First of all Thanks for all the help, I received over the years from MSDN..
Here is my new problem...
I have a SQL table like following table..
State
City
StartDt
EndDt
1
AK
ANCHORAGE
4/1/2007
12/31/2049
2
AK
ANCHORAGE
4/1/2007
12/31/2049
3
AK
ANCHORAGE
5/1/2006
3/31/2007
4
AK
ANCHORAGE
5/1/2006
3/31/2007
5
AK
ANCHORAGE
6/1/2004
4/30/2006
6
AK
ANCHORAGE
6/1/2004
4/30/2006
7
AK
COLDFOOT
10/1/2006
12/31/2049
8
AK
COLDFOOT
10/1/1999
12/31/2049
Now here is what I want to do€¦ 1> Sort the table based on Start Date (the picture shown is already sorted..) for example first 6 rows for AK - Anchorage 2> select the rows with same city (rows 1-6) 3> Select the rows with distinct start date (rows 1-3-5) 4> Change the End Date of the second selected row (row 3 in this case) to I day below the start date of 1 selected row. (4/1/2007 €“ 1 day = 3/31/2007) 5> proceed till end of selected rows.. 1-3-5 6> do the same thing for rows 2 and 4. 7> follow the same procedure for rest of the file.
The selected file should look like this when done..
State
City
StartDt
EndDt
1
AK
ANCHORAGE
4/1/2007
12/31/2049
2
AK
ANCHORAGE
4/1/2007
12/31/2049
3
AK
ANCHORAGE
5/1/2006
3/31/2007
4
AK
ANCHORAGE
5/1/2006
3/31/2007
5
AK
ANCHORAGE
6/1/2004
4/30/2006
6
AK
ANCHORAGE
6/1/2004
4/30/2006
7
AK
COLDFOOT
10/1/2006
12/31/2049
8
AK
COLDFOOT
10/1/1999
9/30/2006
Is there way to do this in SSIS? any recommened appprach>?
Any help with this is highly appreciated.. Thank You..
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