Hi Group!I am having a problem of using SUM under UPDATE statement. I understandthat SQL does not allow me to use SUM in UPDATE, but unfortunately, Ican not find a way to get around it. Can someone please give me someidea? Thanks a million!--Here is the criteria:Under the same PORTFOLIO_ID, if the ACCOUNT_OPENDATE is in the samemonth as the PORTFOLIO_OPENDATE, then sum the account_openamt for thesame PRODUCT, and update the CHECKING_OPENAMT, SAVINGS_OPENAMT,CD_OPENAMT, etc in table PORTFOLIO. For other accounts opened NOT inthe same month as the PORTFOLIO_OPENDATE, just ignore them.--Here are the tablescreate table portfolio(portfolio_id int,portfolio_opendate smalldatetime,checking_openamt money,savings_openamt money,cd_openamt money)insert into portfolio values(1,'2/15/2005',0,0,0)create table account(portfolio_id int,product varchar(20),account_opendate smalldatetime,account_openamt money)insert into account values(1,'checking','2/15/2005',2000)insert into account values(1,'checking','2/20/2005',3000)insert into account values(1,'savings','2/20/2005',3000)insert into account values(1,'cd','5/15/2005',5000)--Ideal Output--id portfolio_opendatechecking_openamtsavings_openamtcd_openamt1 2/15/2005500030000--Here is my query:update portfolioset checking_openamt=sum(b.account_openamt) --problem appears!from portfolio as ajoin account as bon a.id=b.idand year(a.portfolio_opendate)=year(b.account_opendate )and month(a.portfolio_opendate)=month(b.account_openda te)and product ='checking'--and product='savings'--and product='cd'Thanks again!!
hi myself avii am developing one appliacaion in which i am using vb 6 as front end,adodb as database library and sql sever 7 as backend.i want to update one table for which i required data from other table. andiretrive data from second table by giving some condition. when i get data,then to update first table i need to use do while loop. instead of that iwant to use select statement directly in update query.plz give me some help.following is the my queries and its out putStrSql = ""StrSql = "Select * From SalesVchMaterialDesc where TransactionID=" &txtTransactionID.text & ""rsMName.Open StrSql, Conn, adOpenKeysetDo While Not rsMName.EOFStrSql = ""StrSql = "Update StockTable Set Outward=Outward - " &rsMName("Netweight") & ",OutwardQty=OutwardQty - " & rsMName("Qty") & "Where MaterialId=" & rsMName("Material_Name") & " and VoucherDate='" &Format(rsMName("VoucherDate"), "mm/dd/yyyy") & "'RsAdd.Open StrSql, Conn, adOpenStaticrsMName.MoveNextLooprsMName.Closeout put***main querySelect * From SalesVchMaterialDesc where TransactionID=848do while not loopUpdate StockTable Set Outward=Outward - 8.06,OutwardQty=OutwardQty - 1Where MaterialId=221 and VoucherDate='04/01/2004' and SMID=0loop
I am trying to Write an update string for individual partID's. I wrote this query below but it isn't populating the time to test.
SELECT 'UPDATE Parts SET = [TimeToTest]' + ' ' + Convert(varchar, (select test From [dbo].[db_PartsCats] as c Join Parts As P on P.category = C.CatID Where PartID = 48727)) + ' ' + 'WHERE PartID = ' + CONVERT(varchar, P.PartID) From Parts As P Where FRID = 0 And TimeToTest = 0 and TimeToInstall = 0 and TimeToProgram = 0 And TimeToTrain = 0 And manufacturer = 187 Order By categoryMy results:
Should get UPDATE Parts SET = [TimeToTest] 0.5000 WHERE PartID = 48871 But getting Nulls instead
table A: | ID | FRUIT | VEGETABLE | GOOD | -------------------------------------------- | 1 | orange | cabbage | no | | 1 | apple | lettuce | yes | | 1 | kiwi | broccoli | no | | 1 | pear | kale | yes |
table B: | ID | FRUIT | VEGETABLE | ------------------------------- | 1 | apple | lettuce | | 2 | pear | kale |
If the fruit and vegetable in table A is found in table B, then set the GOOD column = yes, else no.
This is what I have so far.
update tableA set GOOD = (case when tableA.id = C.id then 'yes' else 'no' end ) from (select tableA.id as id from tableA A left join tableB B on B.fruit = A.fruit and B.vegetable = A.vegetable) C
I am currently having this problem with gridview and detailview. When I drag either onto the page and set my select statement to pick from one table and then update that data through the gridview (lets say), the update works perfectly. My problem is that the table I am pulling data from is mainly foreign keys. So in order to hide the number values of the foreign keys, I select the string value columns from the tables that contain the primary keys. I then use INNER JOIN in my SELECT so that I only get the data that pertains to the user I am looking to list and edit. I run the "test query" and everything I need shows up as I want it. I then go back to the gridview and change the fields which are foreign keys to templates. When I edit the templates I bind the field that contains the string value of the given foreign key to the template. This works great, because now the user will see string representation instead of the ID numbers that coinside with the string value. So I run my webpage and everything show up as I want it to, all the data is correct and I get no errors. I then click edit (as I have checked the "enable editing" box) and the gridview changes to edit mode. I make my changes and then select "update." When the page refreshes, and the gridview returns, the data is not updated and the original data is shown. I am sorry for so much typing, but I want to be as clear as possible with what I am doing. The only thing I can see being the issue is that when I setup my SELECT and FROM to contain fields from multiple tables, the UPDATE then does not work. When I remove all of my JOIN's and go back to foreign keys and one table the update works again. Below is what I have for my SQL statements:------------------------------------------------------------------------------------------------------------------------------------- SELECT:SELECT People.FirstName, People.LastName, People.FullName, People.PropertyID, People.InviteTypeID, People.RSVP, People.Wheelchair, Property.[House/Day Hab], InviteType.InviteTypeName FROM (InviteType INNER JOIN (Property INNER JOIN People ON Property.PropertyID = People.PropertyID) ON InviteType.InviteTypeID = People.InviteTypeID) WHERE (People.PersonID = ?)UPDATE:UPDATE [People] SET [FirstName] = ?, [LastName] = ?, [FullName] = ?, [PropertyID] = ?, [InviteTypeID] = ?, [RSVP] = ?, [Wheelchair] = ? WHERE [PersonID] = ? ---------------------------------------------------------------------------------------------------------------------------------------The only fields I want to update are in [People]. My WHERE is based on a control that I use to select a person from a drop down list. If I run the test query for the update while setting up my data source the query will update the record in the database. It is when I try to make the update from the gridview that the data is not changed. If anything is not clear please let me know and I will clarify as much as I can. This is my first project using ASP and working with databases so I am completely learning as I go. I took some database courses in college but I have never interacted with them with a web based front end. Any help will be greatly appreciated.Thank you in advance for any time, help, and/or advice you can give.Brian
Ok I have a query "SELECT ColumnNames FROM tbl1" let's say the values returned are "age,sex,race".
Now I want to be able to create an "update" statement like "UPATE tbl2 SET Col2 = age + sex + race" dynamically and execute this UPDATE statement. So, if the next select statement returns "age, sex, race, gender" then the script should create "UPDATE tbl2 SET Col2 = age + sex + race + gender" and execute it.
i was tasked to created an UPDATE statement for 6 tables , i would like to update 4 columns within the 6 tables , they all contains the same column names. the table gets its information from the source table, however the data that is transferd to the 6 tables are sometimes incorrect , i need to write a UPDATE statement that will automatically correct the data. the Update statement should also contact a where clause
the columns are [No] , [Salesperson Code], [Country Code] and [Country Name]
i was thinking of doing
Update [tablename] SET [No] = CASE WHEN [No] ='AF01' THEN 'Country Code' = 'ZA7' AND 'Country Name' = 'South Africa' ELSE 'Null' END
Hello,I am trying to update records in my database from excel data using vbaeditor within excel.In order to launch a query, I use SQL langage in ADO as follwing:------------------------------------------------------------Dim adoConn As ADODB.ConnectionDim adoRs As ADODB.RecordsetDim sConn As StringDim sSql As StringDim sOutput As StringsConn = "DSN=MS Access Database;" & _"DBQ=MyDatabasePath;" & _"DefaultDir=MyPathDirectory;" & _"DriverId=25;FIL=MS Access;MaxBufferSize=2048;PageTimeout=5;" &_"PWD=xxxxxx;UID=admin;"ID, A, B C.. are my table fieldssSql = "SELECT ID, `A`, B, `C being a date`, D, E, `F`, `H`, I, J,`K`, L" & _" FROM MyTblName" & _" WHERE (`A`='MyA')" & _" AND (`C`>{ts '" & Format(Date, "yyyy-mm-dd hh:mm:ss") & "'})"& _" ORDER BY `C` DESC"Set adoConn = New ADODB.ConnectionadoConn.Open sConnSet adoRs = New ADODB.RecordsetadoRs.Open Source:=sSql, _ActiveConnection:=adoConnadoRs.MoveFirstSheets("Sheet1").Range("a2").CopyFromRecordset adoRsSet adoRs = NothingSet adoConn = Nothing---------------------------------------------------------------Does Anyone know How I can use the UPDATE, DELETE INSERT SQL statementsin this environement? Copying SQL statements from access does not workas I would have to reference Access Object in my project which I do notwant if I can avoid. Ideally I would like to use only ADO system andSQL approach.Thank you very muchNono
It appears to update only the first qualifying row. The trace shows a row count of one when there are multiple qualifying rows in the table. This problem does not exist in JDBC 2000.
I'm writing a fairly involved stored procedure. In this Stored Procedure, I have an update statement, followed by a select statement. The results of the select statement should be effected by the previous update statement, but its not. When the stored procedure is finish, the update statement seemed to have worked though, so it is working.
I suspect I need something, like a GO statement, but that doesnt seem to work for a stored procedure. Can anyone offer some assistance?
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
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
Dim lblock As Boolean chkChecked = lblock strSQL = "UPDATE CLIENTS SET " If blnCompleted = True Then strSQL = strSQL & "COMPLETED_DT = '" & Format(Now(), "MM/dd/yyyy") & "', " Else strSQL = strSQL & "LAST_SAVED_DT = '" & Format(Now(), "MM/dd/yyyy") & "', " End If strSQL = strSQL & "COMMENTS = '" & FixString(txtcomments.Text) & "' " _ & "WHERE client_ID = " & iclientID & ""I want to put my booleen value lblock to sql too, I probably need value of it, It is checkbox, called chkblock, . how would I include this to update statement database field for that BLOCK =
Hi, i nid help on update statement. I using 03 and a microsoft sql server 2000 database. I use a more simple example of my error. A Northwind Database is use to update the Region table(RegionDescription) User will 1st go in WebForm2.aspx and enter a id, if found will retrieve the data to WebForm1.aspx. User type "1" and retrieve Eastern to TextBox1. User can choose to update the table by typing in a diff word into TextBox1. But when i type any word(e.g East) the page is refresh back to Webform1.aspx with the not updated data and the database is also not updated. Any idea?
WebForm2.aspx.vb Imports System.Data.SqlClient Public Class WebForm2 Inherits System.Web.UI.PageWeb Form Designer Generated Code Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 'Put user code to initialize the page hereEnd SubPrivate Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Session("id") = TextBox1.Text Response.Redirect("WebForm1.aspx")End Sub End Class
WebForm1.aspx.vb Imports System.Data.SqlClient Public Class WebForm1 Inherits System.Web.UI.Page Web Form Designer Generated CodeDim cnn As New SqlConnection("Data Source=(local); Initial Catalog=Northwind;User ID=******; Password=******") Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 'Put user code to initialize the page here Label1.Text = Session("id") retrieveTitle()End SubSub retrieveTitle() cnn.Open()Dim cmd As New SqlCommand cmd.CommandText = "SELECT * FROM Region WHERE RegionID = '" + Session("id") + "'" cmd.Connection = cnnDim dr As SqlDataReader dr = cmd.ExecuteReader() If dr.Read() Then TextBox1.Text = dr("RegionDescription").ToString End If cnn.Close()End SubSub UpdateTitle(ByVal title As String) cnn.Open()Dim sqlstr As String = "UPDATE Region SET RegionDescription = '" + title + "' WHERE RegionID = '" + Session("id") + "'" Trace.Write(sqlstr)Dim cmd As New SqlCommand(sqlstr, cnn) cmd.ExecuteNonQuery() cnn.Close()End SubPrivate Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
I have a SQL Table with the following columns ID, Date, Meeting, Venue, Notes What Update statement do i need to update a simple grid view in Visual Studio?I have been experementing but when i click update it updates the whole column insted of the one i was trying to update. Please can you help? Thanks
I need some help. please. Here is what I got. From the webpage I can pull the following data to update a table. update Vehicle set Name='TestUnitName' ,Make='TestMake', Model='TestModel', SoftwareVersion='TestVersion', DynamicChange='1', ProviderID='1', Description='TestDescription', VIN='TestVIN', IMEI='TestSIM', EngineTypeId=' ', Phone=' ', MobilePhoneProviderID='' where VehicleID=64 But I also get the error: "The UPDATE statement conflicted with the FOREIGN KEY constraint "FK_Vehicle_EngineTypes". The conflict occurred in database "Telemetry", table "dbo.EngineTypes", column 'EngineTypeId'.The statement has been terminated." How do I solve this issue? Actually what I am trying to do is, when EngineTypeId=' ' , I want to set is to NULL and same for the MobilePhoneProviderID. Any help would be appreciated. Thanks in advance.
I need to set a column value where the id is within a string. However, I need to set the column to a default value if the id is not within the string. Hope that was easy to understand!
ie:
This currently works...
SET @strSQL = 'UPDATE tblTest SET Archive = 1 WHERE RecID IN (' + @IDList + ')
If the ID is not in the list then I want that column set to 0. How can I do this?
Hi I use a update sub, the problem is that i got an error, the error is: Syntax error in UPDATE statement. I guess the UPDATE statement is: strUpdate = "Update tblUsers Set UserName=@UserName, Password=@Password, RetypePassword=@RetypePassword, Email=@Email, Comments=@Comments Where UserID=@UserID"
Remark:I use Acceess DataBase, exactly the same code works fine in SQL, i just changed the DataBase(From Access to SQL).
Is the problem can be in other place? Thank you very much for your assistance.
Hi, I'm having trouble writing this update statement and was wondering if anyone could help me out :
My database is sort of set up lilke this: There are 3 tables: Orders, OrderDetails and Inventory
Orders has a pk called OrderID. OD has several ProductIDs listed for that OrderID Inventory has 2 fields, the pk InventoryID(which is the same as ProductID) and QOH
So OD kinda looks like this: OrderID ProductID Quantity Cost 192 12 2 $10 192 3 1 $12 192 14 2 $50 193 12 1 $11 .... . ... ...
so what i want to do is take each productID for a specific orderid and decrement the inventory for it by OD.quantity
This is what I was trying
UPDATE Inventory Set QOH = QOH - @qty WHERE Inventory.InventoryID IN ( SELECT ProductID FROM OrderDetails WHERE OrderDetails.OrderID = @OrderID and @qty = OrderDetails.Quantity )
I am a SQL Novice - I have a table called 'users' in which I need to modify the user's email id e.g., from seanu@hotmail.com to seanu@yahoo.com and I have over 150 rows where I should be changing 'domain' name only..
Any help with an Update Statement is highly appreciated..
Is there any way to create a "dynamic" update statement in a stored procedure? Lets say I want to choose whether to update all columns in a table or just one. If I want to update just one column, is there a way to make the other columns keeping their values instead of NULL?
ID Field1 Field2 Field3 Field4 1 x y 100 0 2 xx zz 5 0 3 x y 200 1 4 a b 1 1 5 a b 2 0 6 k L 78 1 7 aa bb 25 1 8 k L 15 0
Now the problem is if I want to update a latest record's(if you go by ID)Field4 with 2 for the records where Field1 + Filed2 is unique, can I do this in a single query?
I can select the unique record by the following query
select Field1,Field2 from myTable group by Field1,Field2 having count(ID)>1
Hi first post, so apologies if this is in wrong forum.
I am needing to update a field in one table, where a particular value of another table is TRUE, and update that table based on a common field in both tables.
at the moment my query is:
IF EXISTS (SELECT * FROM _tblSnapShotAUSProfServicesOrderLines_Daily WHERE _tblSnapShotAUSProfServicesOrderLines_Daily.Produc tRelProductName like 'Prof%') UPDATE OrderHeader_details SET ServicesSold = 'Y' WHERE OrderHeader_details.OrderRef = _tblSnapShotAUSProfServicesOrderLines_Daily.OrderR ef
In its current format, I get the column prefix is incorrect which makes sense sort of. No matter which way I change this, I cannot get the query to work. I one form, it works but essentially performs two seperate statements, one with the select, and one with the update which unfortunately updates every row in the table.
I need help with a sql update statement i need it to convert a datetime value to a specific format. For some reason it statement will only update the row only when i convert the datetime value to a varchar, i ran it in mssql sql server management studio and it works, the database is a mssql 2000 i think. If i try to compare the datetime value and they are both DateTime values it fails, if i convert them to varchar and run them they succeed, what i also noticed is when when are date values are that the value i passed in the query is that they are in a different format, i guess the database stores them as mon/dd/yyyy hh:mm:ss. but when i run the query that failed i get this as the results of the values from variables @Date1 & @Date2: They are the same and they failed. So if anyone knows any thing any help is surely appreciated this really sucks.
Failed Date 1: Sep 23 2007 9:54PM Date 2: Sep 23 2007 9:54PM ---------------------------------------------
Need help with making this work in C#:
Code:
string sql = string.Format( "UPDATE [Contact Sheet] SET CallAttempt1 = {0}, CallAttempt2 = {1}, " + "CallAttempt3 = {2}, Status = '{3}' WHERE ContactID = {4} AND ModifiedDate = 'CONVERT(VARCHAR(50), {5}, 0)'", ..............................);
This statement ran in MSSQl Studio Management and works:
Code:
DECLARE @Date1 AS VARCHAR(50) DECLARE @Date2 AS VARCHAR(50)
SET @Date2 = CONVERT(DATETIME, '9/23/2007 9:54:40 PM', 0); SET @Date1 = (SELECT Convert(VARCHAR(50), ModifiedDate, 0) FROM [Contact Sheet] WHERE CustomerID = 22);
IF @DATE1 = @DATE2 BEGIN PRINT 'Success' END ELSE BEGIN PRINT 'Failed' -- PRINT @TmpDate PRINT 'Date 1: ' + @DATE1 PRINT 'Date 2: ' + @Date2 END
This one fails everytime:
Code:
DECLARE @Date1 AS DATETIME DECLARE @Date2 AS DATETIME
SET @Date2 = CONVERT(DATETIME, '9/23/2007 9:54:40 PM', 0); SET @Date1 = (SELECT Convert(DATETIME, ModifiedDate, 0) FROM [Contact Sheet] WHERE CustomerID = 22);
IF @DATE1 = @DATE2 BEGIN PRINT 'Success' END ELSE BEGIN PRINT 'Failed' -- PRINT @TmpDate PRINT 'Date 1: ' + CONVERT(VARCHAR(50), @DATE1, 0) PRINT 'Date 2: ' + CONVERT(VARCHAR(50), @Date2, 0) END
Hey everyone, first time poster, and this problem has been bugging me all morning.
I am attempting to UPDATE a temp table (#Patient_Bill) with amounts derived from another table using a stored procedure that is used by a Powerbuilder Data Window.
Here is my statement:
UPDATE #Patient_Bill SET balance_amount = (select sum(balance_amount) from Payment py WHERE #Patient_Bill.patient_id = b.patient_id) WHERE #Patient_Bill.patient_id = Payment.Patient_id
My goal is whenever the Powerbuilder data window is called that their "balance_amount" is shown on the data window (only one line since it's specific to patient).
However, whenever this is called I get the following error:
Insert Error: Column name or number of supplied values does not match table definition
Is my SQL code above pulling too many lines? I want only one line to populate in my data window based off the specific Patient_id.
I am trying to update three fields in a tbl (c) from the sum of another tbl (b). But also tbl (b) also needs to be joined to tbl (a) to meet a criteia.
I also do not want lengthy statement. Could someone tell me what I am doing wrong with my statement below?
UPDATE DBO.HIST3 SET INTRA_WGT = SUM(DBO.HIST2.EXT_TUBE_WGT), INTRA_MKT = SUM(DBO.HIST2.EXT_MKT_AMT), INTRA_NET = SUM(DBO.HIST2.GROSS_AMOUNT) WHERE DBO.HIST3.SHIP_PLANT,DBO.HIST3.BILL_DATE IN
(SELECT DBO.HIST2.SHIP_PLANT,DBO.HIST2.BILL_DATE FROM DBO.HIST2 INNER JOIN DBO.HIST1 ON DBO.HIST2.INVOICE_NBR = DBO.HIST1.INVOICE_NBR WHERE INVOICE_TYPE = 'IP' GROUP BY DBO.HIST2.BILL_DATE ,DBO.HIST2.SHIP_PLANT)
The table (Hist3) and (Hist2) needs to be joined by two fields to get correct results, but I get the following error msgs. Msg: An aggregate may not appear in the set list of an UPDATE statement.
Update @table1 set col1=(select col1 from table2 where table2.col2=@table1.col2) where @table1.col2=table2.col2 here @table1 is a table variable. I can not get thro this update.Please help. regards, harsh