table2 is intially populated (basically this will serve as historical table for view); temptable and table2 will are similar except that table2 has two extra columns which are insertdt and updatedt
process: 1. get data from an existing view and insert in temptable 2. truncate/delete contents of table1 3. insert data in table1 by comparing temptable vs table2 (values that exists in temptable but not in table2 will be inserted) 4. insert data in table2 which are not yet present (comparing ID in t2 and temptable) 5. UPDATE table2 whose field/column VALUE is not equal with temptable. (meaning UNMATCHED VALUE)
* for #5 if a value from table2 (historical table) has changed compared to temptable (new result of view) this must be updated as well as the updateddt field value.
Hi SQL fans,I realized that I often encounter the same situation in a relationdatabase context, where I really don't know what to do. Here is anexample, where I have 2 tables as follow:__________________________________________ | PortfolioTitle|| Portfolio |+----------------------------------------++-----------------------------+ | tfolio_id (int)|| folio_id (int) |<<-PK----FK--| tfolio_idfolio (int)|| folio_name (varchar) | | tfolio_idtitle (int)|--FK----PK->>[ Titles]+-----------------------------+ | tfolio_weight(decimal(6,5)) |+-----------------------------------------+Note that I also have a "Titles" tables (hence the tfolio_idtitlelink).My problem is : When I update a portfolio, I must update all theassociated titles in it. That means that titles can be either removedfrom the portfolio (a folio does not support the title anymore), addedto it (a new title is supported by the folio) or simply updated (atitle stays in the portfolio, but has its weight changed)For example, if the portfolio #2 would contain :[ PortfolioTitle ]id | idFolio | idTitre | poids1 2 1 102 2 2 203 2 3 30and I must update the PortfolioTitle based on these values :idFolio | idTitre | poids2 2 202 3 352 4 40then I should1 ) remove the title #1 from the folio by deleting its entry in thePortfolioTitle table2 ) update the title #2 (weight from 30 to 35)3 ) add the title #4 to the folioFor now, the only way I've found to do this is delete all the entriesof the related folio (e.g.: DELETE TitrePortefeuille WHERE idFolio =2), and then insert new values for each entry based on the new givenvalues.Is there a way to better manage this by detecting which value has to beinserted/updated/deleted?And this applies to many situation :(If you need other examples, I can give you.thanks a lot!ibiza
I have a table #vert where I have value column. This data needs to be updated into two channel columns in #hori table based on channel number in #vert table.
CREATE TABLE #Vert (FILTER VARCHAR(3), CHANNEL TINYINT, VALUE TINYINT) INSERT #Vert Values('ABC', 1, 22),('ABC', 2, 32),('BBC', 1, 12),('BBC', 2, 23),('CAB', 1, 33),('CAB', 2, 44) -- COMBINATION OF FILTER AND CHANNEL IS UNIQUE CREATE TABLE #Hori (FILTER VARCHAR(3), CHANNEL1 TINYINT, CHANNEL2 TINYINT) INSERT #Hori Values ('ABC', NULL, NULL),('BBC', NULL, NULL),('CAB', NULL, NULL) -- FILTER IS UNIQUE IN #HORI TABLE
One way to achieve this is to write two update statements. After update, the output you see is my desired output
UPDATE H SET CHANNEL1= VALUE FROM #Hori H JOIN #Vert V ON V.FILTER=H.FILTER WHERE V.CHANNEL=1 -- updates only channel1 UPDATE H SET CHANNEL2= VALUE FROM #Hori H JOIN #Vert V ON V.FILTER=H.FILTER WHERE V.CHANNEL=2 -- updates only channel2 SELECT * FROM #Hori -- this is desired output
my channels number grows in #vert table like 1,2,3,4...and so Channel3, Channel4....so on in #hori table. So I cannot keep writing too many update statements. One other way is to pivot #vert table and do single update into #hori table.
The objective is to identify orders where an order fee has been applied incorrectly. I have multiple orders per customer, my table contains an orderID and a customerID. Currently if the customer places additional orders before the previous orders have been closed/cancelled, then additional fees are being applied.
Let's say I'm comparing order #1 to order #2. I need to identify these rows where the following is true:-
The CustID is the same.
Order #2 has a more recent order date.
Order #2 has a FeeDate Before the CancelledDate of Order #1 (or Order #1 has no cancellation date).
So in the table the orderID:2835692 of CustID: 24643 has a valid order fee. But all the subsequently placed orders have fees which were applied before the first order was cancelled and so I want to update the FeeInvalid column with a 'Y'. The first fee will always be valid.
I think I understand why the code I am trying doesn't achieve the result I want but I can't figure out how to write it correctly. Below is one example of code I've tried and also code to create the table and insert some test data.
update t1 SET FeeInvalid = 'Y' FROM MockData t1 Join MockData t2 on t1.CustID = t2.CustID WHERE t1.CustID = t2.CustID AND t2.OrderDate > t1.OrderDate AND t2.FeeDate > t1.CancelledDate CREATE TABLE [dbo].[MockData]( [OrderID] [float] NULL,
I have 2 identical tables one contains current settings, the other contains all historical settings.I could create a union view to display the current values from table A and all historical values from table B, butthat would also require a Variable to hold the tblid for both select statements.
Q. Can this be done with one joined or conditional select statement?
DECLARE @tblid int = 501 SELECT 1,2,3,4,'CurrentSetting' FROM TableA ta WHERE tblid = @tblid UNION SELECT 1,2,3,4,'PreviosSetting' FROM Tableb tb WHERE tblid = @tblid
I am relatively new to SQL and as a project I have been asked to create the SQL for a simple database to record train details. I want to implement a check constraint which will prevent data from being inserted into a table if the weight of the train is more than the maximum towing weight of the locomotive. FOr instance, I need to add the unladen weight and maximum capacity of each wagon (located in the wagon type table) and compare it against the locomotive maximum pulling weight (the locomotive class table). I have the following SQL but it will not work:
check((select SUM(fwt.unladen_weight+fwt.maximum_payload) from hauls as h,freight_wagon as fw,freight_wagon_type as fwt,train as t where h.freight_wagon_serial_number = fw.freight_wagon_serial_number and fw.freight_wagon_type = fwt.freight_wagon_type and h.train_number = t.train_number) < (select lc.maximum_towing_weight from locomotive_class as lc,locomotive as l,train as t where lc.locomotive_class = l.locomotive_class and l.locomotive_serial_number = t.locomotive_serial_number))
The hauls table is where the constraint has been placed and is the intermediary table between train and freight wagon.
I may not have explained this very well; but in short, i need to compare the sum of two values in one table against a values located in another table...At present I keep getting a message telling me the sub query cannot return more than one row.
I need to replace all the "User Friendly Names" with "System Names" in the calculations, i.e., I need "Sales Units" to be replaced with "cSalesUnits", "AUR" replaced with "cAUR", "Comp Sales Units" with "cCompSalesUnits", and "Comp AUR" with "cCompAUR". (It isn't always as easy as removing spaces and added 'c' to the beginning of the string...)
I have created a CTE of all the "Look-up" values, and have tried all kinds of joins, and other functions to achieve this, but so far nothing has quite worked.
How can I accomplish this?
Here is some SQL for set up. There are over 500 formulas that need updating with over 400 different "look up" possibilities, so hard coding something isn't really an option.
Hi,I have table with three columns as belowtable name:expNo(int) name(char) refno(int)I have data as belowNo name refno1 a2 b3 cI need to update the refno with no values I write a query as belowupdate exp set refno=(select no from exp)when i run the query i got error asSubquery returned more than 1 value. This is not permitted when thesubquery follows =, !=, <, <= , >, >= or when the subquery is used asan expression.I need to update one colum with other column value.What is the correct query for this ?Thanks,Mani
Gurus, I have two list boxes, user can move items back n forth, from second listbox I am inserting values into a table. So far everything is working fine. Now I want to delete all the existing values from the table before inserting evertime..Please help me in this I dont know what to do. thanks kalloo
I'm trying to checking my production table table_a against a working table table_b (which i'm downlading data to)Here are the collumns i have in table_a and table_bDescription | FundID (this is not my PK) | Money I'm running an update if there is already vaule in the money collumn. I check to see if table_a matches table_b...if not i update table a with table b's value where FundID match up.What i'm having trouble on is if there is no record in table_a but there is a record in table_b. How can I insert that record into table_a? I would like to do all of this (the update and insert statement in one stored proc. if possible. )If anyone has this answer please let me know.Thanks,RB
Please be easy on me...I haven't touched SQL for a year. Why given;
Code Snippet USE [Patients] GO /****** Object: Table [dbo].[Patients] Script Date: 08/31/2007 22:09:29 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO SET ANSI_PADDING ON GO CREATE TABLE [dbo].[Patients]( [PID] [int] IDENTITY(1,1) NOT NULL, [ID] [varchar](50) NULL, [FirstName] [nvarchar](50) NULL, [LastName] [nvarchar](50) NULL, [DOB] [datetime] NULL, CONSTRAINT [PK_Patients] PRIMARY KEY CLUSTERED ( [PID] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO SET ANSI_PADDING OFF
I have created a table Table with name as Varchar and id as int. Now i have started inserting the rows like, insert into Table values ('arun',20).Yes i have inserted a row in the table. Now i have got the values " arun's ", 50. insert into Table values('arun's',20) My sqlserver is giving me an error instead of inserting the row. How will you solve this problem?
instead of insert into command sqlcom.CommandText = "insert into Approve_Overtime(syainNo,ninka_nen_from,ninka_gatsu_from)values(@syainNo,@ninka_nen_from,@ninka_gatsu_from)
Hi Guys I already searched for one day and didn't find any solution. Unfortunately I can't update my dataset. It works when I remove the string "WHERE ID = ?" in the UpdateCommand but then it updates all the records. I think it must be something obvious which I just don't see:(There are two tables; tblArtists and tblCountries which are connected together with a Inner Join. Now, I need the ID from the table Artists to update the dataset. How can I get it?Here the code:....SelectCommand="SELECT tblArtists.ID AS IDArtists, tblArtists.ArtistName, tblArtists.FirstName, tblArtists.LastName, tblArtists.Address, tblArtists.PLZ, tblArtists.City, tblArtists.Region, tblArtists.Country_ID, tblArtists.MusicStyles, tblArtists.HomeDJ, tblArtists.Active, tblArtists.CDate, tblArtists.Description, tblCountries.ID AS IDCountries, tblCountries.Country, tblArtists.Producer, tblArtists.Picture, tblArtists.Homepage, tblArtists.Phonenumber, tblArtists.eMail FROM (tblCountries INNER JOIN tblArtists ON tblCountries.ID = tblArtists.Country_ID) WHERE (tblArtists.Active = ?) AND (tblArtists.HomeDJ = ?) AND (tblArtists.Producer = ?)" UpdateCommand="UPDATE tblArtists SET ArtistName = ?, FirstName = ?, LastName = ?, Address = ?, PLZ = ?, City = ?, Region = ?, Country_ID = ?, MusicStyles = ?, HomeDJ = ?, Active = ?, Description = ?, Producer = ?, Picture = ?, Homepage = ?, Phonenumber = ?, eMail = ? WHERE ID = ?"> <SelectParameters> <asp:ControlParameter ControlID="activeRadioButton" Name="Active" PropertyName="Checked" Type="Boolean"/> <asp:ControlParameter ControlID="homedjRadioButton" Name="HomeDJ" PropertyName="Checked" Type="Boolean"/> <asp:ControlParameter ControlID="producerRadioButton" Name="Producer" PropertyName="Checked" Type="Boolean"/> </SelectParameters> <UpdateParameters> <asp:Parameter Name="ArtistName" Type="String" Size="254" /> <asp:Parameter Name="FirstName" Type="String" Size="254" /> <asp:Parameter Name="LastName" Type="String" Size="254" /> <asp:Parameter Name="Address" Type="String" Size="254" /> <asp:Parameter Name="PLZ" Type="String" Size="254" /> <asp:Parameter Name="City" Type="String" Size="254" /> <asp:Parameter Name="Region" Type="String" Size="254" /> <asp:Parameter Name="Country_ID" /> <asp:Parameter Name="MusicStyles" Type="String" Size="254" /> <asp:Parameter Name="HomeDJ" Type="Boolean" /> <asp:Parameter Name="Active" Type="Boolean" /> <asp:Parameter Name="Description" Type="String" /> <asp:Parameter Name="Producer" Type="Boolean" /> <asp:Parameter Name="Picture" Type="String" Size="254" /> <asp:Parameter Name="Homepage" Type="String" Size="254" /> <asp:Parameter Name="Phonenumber" Type="String" Size="50" /> <asp:Parameter Name="eMail" Type="String" Size="50" /> <asp:Parameter Name="original_IDArtists" Type="Int32" /> </UpdateParameters> </asp:SqlDataSource> GreetingsPat
B IDIDAVALUE 1|1|12 2|1|34 3|2|17 4|3|4 5|1|22 6|3|1
I want to update A with values from b , so the value2 from a= value from b but only with latest corresponding data based on b.id so after updtate a looks like:
IDVALUE1VALUE2 1 |a |22 couse max id from B with ida=1 is 5 and so the value is 22, so A.value2=22 2 |v |17 couse max id from B with ida=2 is 3 and so the value is 17so A.value2=22 3 |c | 1 couse max id from B with ida=3 is 6 and so the value is 1 so A.value2=1 4 |g |12 couse there is no ida=4 in B
I have faced a situation that when i try to update a page. Some values can be updated while some cannot. I try to print the executed SQL query and get the following1 "UPDATE orders SET 2 cust_id=15,po_code='PO20060610', 3 po_amt=10000.0000, 4 add_charges=0, 5 commission='eeeeeee', 6 lab_charges=0, 7 fty_dis=0, 8 pay_trm='adasds', 9 cust_dis=0, 10 trade_trm_desc='', 11 curr_rate=1, 12 ship_expense=0, 13 shipmark='eng ship mard new2', 14 sidemark='Eng Side Mark new333' 15 ,inner_box='Eng Inner Box new333', 16 confirmation='rend confirmation2', 17 contract='end contact23', 18 internal_remark='testing testing 26/6/2007 333', 19 rec_curr_rate=0,rec_amt=0,shipmark_attach='', 20 sidemark_attach='',inner_box_attach='', 21 ord_type=1,status=2,ord_confirm_code='', 22 commission_type=1,sidemark_lang='English', 23 curr_code='HKD',unit_code='PCS', 24 trade_trm='FOB Hong Kong',rec_curr='USD', 25 ord_date='2006/06/10', po_date='01/01/2007',exp_delivery_date='01/01/2007', 26 act_delivery_date='01/01/2007', pay_start_date='10/10/06',pay_end_date='10/10/06',upd_time='2007/03/15 15:41:14' WHERE ord_id=292;Set @ord_id=292;"
The fields sidemark, inner_box, internal_remark cannot update, while others can. I think it's really strange.... since i have no idea why some can be updated while some others and the SQL seems to me is correct. Please give me some advices on solving this. Thank you.
I have a table say #temp1 with coulmn Id and Description and I do have another table #temp2 with column id and Projectdescription but in #temp2 there could be more then one value against one id like the data in #temp2 is look like
id Projectdescription 1 Computer project 1 update in computer project 1 another update in computer 2 Physics project 2 another update
but #temp1 has only one accurance of id and data initially looks like id Description 1 NUll 2 NUll and I would like to update this table description from #temp2 Projectdescription column so that data in #temp1 table look like after update
id Description 1 Computer project,update in computer project, another update in computer
2 Physics project, another update
I mean I would like to have concatination form of Projectdescription in description column against specific ID I can achieve this by using UDF but i dont want to use that I just want to do it by update statement not even by using cursor
Both have an identical table called "Codes" containing billing numbers and prices.
Database B is one I use for testing, and is out of date. Is there an easy way to load the values from Table_A.codes into Table_B.codes?
I know how to do an update from one table to another within the same database, but am clueless how to do it when the data reside in separate databases.
Hi there...Is it possible to write an UPDATE or INSERT query, where the new value comesfrom an array? For example:UPDATE table_a SET column_x = [@array1]WHERE column_y = [@array2];It's a query (for argument's sake called query1) in an Access database,which I'm accessing as a stored procedure through PHP, so I would run somephp code that looked possibly like this:$array1 = array("a","b","c","d");$array2 = array(1,2,3,4);$str_sql = "exec query1 $array1, $array2";my_run_query_function($str_sql);But is it possible? The information I can find about it seems to say that ithas to be an array created inside the query, but if it's a stored procedure,this isn't possible, is it?Hope someone can help...Plankmeister.
When a record is inserted or updated records in Table1 I want a record to be inserted into table3 for each record ID that is in table2 if the table2.id does not already exist in table3. What is the best way to do this? Could this be done with a trigger? If it could how would I write such a trigger. I have never written one before and this sounds like a hand full for my first effort. Your help will be greatly appreciated.
Hi, I am trying to use a formView with an update button to update individual records in an sql database. (when i click update it doesnt perform the update and just refreshes the page. ) One of the fields in my records is a NULL - this is also one of the fields that i need to update. When i manually go into the database and enter some data, and then go back to my form, it updates fine, but as soon as i delete the data from the field, it returns to NULL and im back to square one. Any Ideas on how to get around this problem?THanks
I am new to both ASP.net and this forum. I have seen some posts close to this, but none address this problem.
I have a SQL Server database on JOHN1 called 'siu_log' with a table called 'siu_log'. It has two fields: Scenarios char[20] and Machines char[20].
I have been adapting code from Build Your Own ASP.NET Website in C# & VB.NET by Zac Ruvalcaba to learn the language. Much of what you will see is his work adapted for my use.
Sub dg_Update(ByVal s As Object, ByVal e As DataGridCommandEventArgs) Dim strMachineName, strScenarioName As String Dim intResult As Integer strScenarioName = Trim(scenariosDataGrid.DataKeys(e.Item.ItemIndex)) strMachineName = CType(e.Item.FindControl("txtMachine"), TextBox).Text cmd = New SqlCommand("UPDATE siu_log SET Machines=@Machine " & _ "WHERE Scenarios=@Scenario", conn) cmd.Parameters.Add("@Machine", strMachineName) cmd.Parameters.Add("@Scenario", strScenarioName) conn.Open() intResult = cmd.ExecuteNonQuery() resultLabel.Text = "The result was " & intResult & "." conn.Close() scenariosDataGrid.EditItemIndex = -1 BindData() End Sub
The problem is the strMachineName variable always contains the previous contents of the text box -- not the new one. This makes the UPDATE query just push the old data back into the table.