Sql query to Load only new records,or update old records
Hi,
I need a query (not stored procedure) to insert only new records otherwise update existing records.
I tried by creating "Merge statement in SQl", but the sql query is wrong,it is not updating,always inserting records(replicating..1,2,4,8,16,32..).
below is my sample query,
Here "FACT_mytbl -FCT" is my fact table.(which need to update if already records found ,otherwise insert as new records).
*Inside select ---the table E_tbl1,E_tbl2 is the business logic table ,using this two table only ,"FACT_mytbl" was created .So the "S" alias will be the source
table and "FCT" will be target table. based on this we have to insert or update records.
---Query starts-------------------------------------
MERGE INTO [FACT_mytbl] FCT
USING (
SELECT
FCT1.ID
,FCT1.PKcol1
,FCT1.FKcol1
,FCT1.col1
,FCT1.col2
, FCT1.col3
FROM [FACT_mytbl] FCT1 WITH(NOLOCK)
LEFT JOIN dbo.E_tbl1 CT WITH(NOLOCK)
ON CT.PKcol1=FCT1.PKcol1
LEFT JOIN dbo.E_tbl2 CT1 WITH(NOLOCK)
ON CT1.PKcol1=FCT1.PKcol1
) S
ON FCT.PKcol1 = S.PKcol1
WHEN MATCHED AND (FCT.PKcol1 ! = S.PKcol1 ) THEN
UPDATE SET
FCT.col1
,FCT.col2
,FCT.col3
WHEN NOT MATCHED THEN
INSERT VALUES
S.ID
,S.PKcol1
,S.FKcol1
,S.col1
,S.col2
, S.col3
--query ends----------------
any suggestions,
Thanks,
R.B
Hi Bhupesh_Rajasekaran,
According to your description, if you want to insert only new records which does not exist in destination and update existing records which does exist in destination. We usually accomplish these in two statement.
1.A join statement to update records.
2.A insert statement for new records.
Also we can use MERGE in SQL Server to insert, update at the same time. You specify a "Source" record set and a "Target" table, and the join between the two. You then specify the type of data modification that is to occur when the records between the two
data are matched or are not matched. For more information, there is an similar example about merge in SQL Server, you can review the following article.
http://www.codeproject.com/Tips/590085/Merge-in-SQL-Server
Regards,
Sofiya Li
Sofiya Li
TechNet Community Support
Similar Messages
-
SQL- Query that return only one record
Hello,
is it possible to execute a pure SQL-Query which returns only one row although multiple rows are found.
It is no problem in PL/SQL, but I have no idea if the same is also possible in SQL.
thanks in advance
MichaelWhy not? There are 4 records in this table, but only selected one.
SQL> with t
2 as
3 (
4 select '#%$@#$@$@##$' Addr from dual
5 union all
6 select '18 Jalan Scott' from dual
7 union all
8 select '18 Lemana St' from dual
9 union all
10 select '32-penstation' from dual
11 union all
12 select '99999999999' from dual
13 )
14 select addr
15 from t
16 where rownum =1
17 /
ADDR
#%$@#$@$@##$
SQL>Cheers
Sarma. -
Need help in SQL query to get only distinct records
Hi all.
I am new to oracle SQL and i want to write a query to get only distinct values from 2 tables.
for example i hade 2 tables table1(employee_id,employee_no,grade) and another table2 with same structure.
for example data in table1 is
Employeeid employeeno Grade
1 101 A
1 101 B
1 101 E
1 101 D
and data in table 2 is
Employeeid employeeno Grade
1 101 A
1 101 B
1 101 E
i want to display only the fourth row like the data that doesnt exist in table2 i,e (1 101 D)
I had too much records in both tables and i jst want to see the records that is in table 1 not in table 2 only.
employeeid and employeeno are the same in both tables
I hope u understand my query. I user left outer join and right outer join bt it displays all the results that and matching and unmatching. I want jst unmatched records.
Any help is highly Appreciated.
Thanx in Advance.
I am using oracle 10G on windowsTry MINUS:
http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/queries004.htm#i2054381
SQL> -- generating sample data:
SQL> with t1 as (
2 select 1 employeeid, 101 employeeno, 'A' grade from dual union
3 select 1, 101, 'B' from dual union
4 select 1, 101, 'E' from dual union
5 select 1, 101, 'D' from dual
6 )
7 , t2 as (
8 select 1 employeeid, 101 employeeno, 'A' grade from dual union
9 select 1, 101, 'B' from dual union
10 select 1, 101, 'E' from dual
11 )
12 --
13 -- actual query:
14 --
15 select employeeid
16 , employeeno
17 , grade
18 from t1
19 minus
20 select employeeid
21 , employeeno
22 , grade
23 from t2;
EMPLOYEEID EMPLOYEENO G
1 101 D
1 row selected. -
Sqlldr is loading only 1st record from xml document
Hi,
I am trying to load XML doc with multiple records using sql*loader.
I have registered my XSD perfectly.
This is my control file
LOAD DATA
INFILE *
INTO TABLE Orders APPEND
XMLType(xmldata)
FIELDS(
xmldata LOBFILE (CONSTANT FULDTL_2.xml)
TERMINATED BY '???')
BEGINDATA
FULDTL_2.xml
-- Here, what I have to give for TERMINATED BY '???'
My xml doc
<Order ID="146120486" Status="CL" Comments="Shipped On 08/05/2008"/>
<Order ID="143417590" Status="CL" Comments="Handset/Device has been received at NRC" ShipDate=""/>
sqlldr is loading only 1st record from the file.
How can I make it to load all the records from my xml doc.
Thanks in advance.thanks for both the replies above - essentially the same correct solution.
something worth noting now that I've written and tested both a SAX solution and a DOM solution is that there is a significant (4 x) time penalty using SAX.
I considering dividing the vector I am storing/recovering into chunks and saving each chunk separately using DOM to speed things up...
any thoughts on this approach? -
SQL query to get last 10 records in the table?
Hi,
Can anyone tell me the SQL query to get last 10 records in the table?
Thanks!!
MCPPlease, define what "last" means. Sets are unordered by definition, so if you want to retrieve rows from a table in a specific order you need to specify what that order is - e.g. by maintaining a value in a column (or a combination of columns) that you can use in the ORDER BY clause of the SELECT statement.
If, for instance, you kept the time when the row was inserted in a special column (InsertedTime), you could use this in your query like this:
select top (10)
<column list>
from <table or view>
where <restriction(s)>
order by InsertedTime desc;
ML
Matija Lah, SQL Server MVP
http://milambda.blogspot.com -
Image caching. Loading only new images
we develop huge game and it takes some time to load on startup because of tons of assets. Once per week or 2 weeks it is updated to new version which might bring few new assets or update previous ones.
So now we are trying to find the way that will allow flash to load only new/updated assets and the rest to fetch from cache. But we haven't succeeded yet. Does anybody have any idea?thanks for the responce. Unfortunatelly, my English is not perfect. You mean sending to flash (flashvars) a variable containing a set of images to load so those ones that are not in the list are to be taken from cache?
-
SQL Query to retrieve the All records based on the Max Dates.
Hello all,
I am trying to retrieve the newest record based on the date field ( nextDate ).
Currently there are only 4 records in the MC_Maintenance table and two in the Machine table.
Machine table
MC_id EquipID
1 0227
MC_id EquipID
2 0228
MC_Maintenance table
Maint_id MC_id Next_maint
1 2 08/25/2010
2 2 07/01/2010
3 1 06/11/2010
4 1 07/11/2010
What I am trying to accomplish is,
list the two machines from the Machine table with the MAX(Next_maint) controlling the MC_Maintenance output list
These are the records that I would like to Display.
Maint_id MC_id Next_maint
1 2 08/25/2010
4 1 07/11/2010
Below is the SQL Query
SELECT
MC.MC_ID as ID,
MC.complete_Date as completed,
MC.next_maint as nextDate,
MC.maint_notes as Notes,
MC.facility as Facility,
M.EquipId,
M.name as name,
M.SerialNumber as SN,
M.dept as dept,
M.Freq as freq
From MC_Maintenance MC, Machine M
where MC.MC_ID = M.MC_ID
' USING MAX(nextDate )
Any ideas would help.
TJI would have thought that was a simple group by problem?
SELECT M.EquipID, MC.MC_ID, Max(MC.next_maint)
FROM MC_Maintenance MC INNER JOIN Machine M ON MC.MC_ID = M.MC_ID
GROUP BY M.EquipID, MC.MC_ID -
Report from SQL Query -Excel format only show the first page
Hi,
I have some Reports from SQL Query. In the display options, I choose Excel as default format. The Excel documents only show the first page. If I choose HTML as default format, it shows every rows.
Please advise on how to have a complete Excel document as HTML format does.
Thanks a lot.
Lina HanI beleive when you export Oracle reports to Excel it is the Data that is transferred along with Column Names.
You cannot export the variables defined on the report.
Hence you will not be able to export the Footer to excel. (Still looking into it will let you know if i find anything interesting)
Regards,
Bhushan Salgar -
SQL Query criteria eliminates too many records
This SQL query results in zero out of 268 records due to the criteria of (((Products.ProductFamily)<=0))
SELECT images.url_img, images.alt_img, images.productid_img, Products.ProductFamily, Products.ID
FROM images LEFT JOIN Products ON images.productid_img = Products.ID
WHERE (((Products.ProductFamily)<=0));
However, if you change the <=0 to >0, the correct 140 out of 268 records show up. So if 140 records are greater than zero, shouldn't the remaining 128 records be less than or equal to zero? How do I get the results that are <=0 to show up?
FYI - Products.ProductFamily data type is numeric, field size is integer, decimal places is auto, default value is 0, required is No, indexed is NoYes, but can you still answer the question? I am trying to determine if the problem is in the join or the where clause. What happens if you remove the join and still include results from the product table? Can you give an example of data for a few rows (both tables) that are not working as expected?
-
Handling sql query in jsp while extracing records from 3 tables
hi to one and all,
i want to implement the sql query given below in jsp in execute query statement . the query is working in sql but not when implemented using jsp. please help me in resolving this.
Query
SELECT e.Department , e.ETitle , s.basic , s.da, c.address1 , c.address2 from Employee e , Salary s , Contactdetails1 c where e.id = s.id and e.id =c.idIt would help if you gave us a little more info to go on like;
a) post your code
b) post the error message the compiler is giving you -
Regarding Select query to select only 1000 records in Internal Table.
Hello Friends,
Please explain me to how to Select only 1000 records from data base table?
For Example
SELECT * INTO TABLE ITAB OR SELECT * INTO ITAB
FROM EKKO FROM EKKO
WHERE EBLEN IN S_EBLEN. WHERE EBLEN IN S_EBLEN
(Currently i am using) UP TO 1000 ROWS.
ENDSELECT. (I do not want to use)
In this case Internal table may be store more then 1000 records. But i want to select first 1000 records.
Please explain me.
Regards
AmitHi,
TABLES : ekko.
selection-screen begin of block b1 with frame title text_t01.
SELECT-OPTIONS: S_EBELN for ekko-EBELN.
selection-screen end of block b1.
DATA itab TYPE STANDARD TABLE OF ekko.
SELECT *
FROM ekko
INTO TABLE itab
UP TO 1000 ROWS
WHERE EBELN IN S_EBELN.
Thanks,
Sri. -
SQL QUERY updateable report with APEX_ITEM fields to update hidden columns
Here is my SQL query:
select
"EMPLOYEE_ID",
"PUBLICATION_ID",
"TITLE",
'<NOBR>1. ' || APEX_ITEM.TEXT(101,CODE1,2,3) || ' ' ||
APEX_ITEM.TEXT(102,CODE1_PCT,2,3) || ' %</NOBR><BR>' ||
'<NOBR>2. ' || APEX_ITEM.TEXT(103,CODE2,2,3) || ' ' ||
APEX_ITEM.TEXT(104,CODE2_PCT,2,3) || ' %</NOBR><BR>' ||
'<NOBR>3. ' || APEX_ITEM.TEXT(105,CODE3,2,3) || ' ' ||
APEX_ITEM.TEXT(106,CODE3_PCT,2,3) || ' %</NOBR>' rfcd_codes,
APEX_ITEM.DISPLAY_AND_SAVE(100,CODE1) hidden_rfcd1,
mycomments
from "#OWNER#".mytable
I have 3 code fields with their percentages (_pct). I have concatinated them so I can format them nicely on the page.
I have create a process 'on-submit and before computations and validations' where I was hoping to assign my table columns (eg the code and pct columns) from the APEXITEMs in my select statement.
I can get the values from these (APEX_ITEM) fields by referencing APEX_APPLICATION.G_F10(i) etc.... so thats cool.
But my problem is how do I reference the table columns so I can assign them.
I am using a 'Multi Row Update' process to perform the update to the database.
P.S. mycomments column is working fine. It gets updated nicely but its just those other APEX_ITEM fields.I don't have the apex_application.g_f01(i) referenced in the page source...In the page source you wouldn't find anything by that name
Identify the tabular form's checkbox column in the page(firebug/chrome developer panel makes this easy)
It should be like
<input id="..." value="" type="checkbox" name="fXX" >we are interested in the name attribute , get that number (between 01 and 50)
Replace that number in the code, for instance if it was f05 , the code would use
apex_application.g_f05
--i'th checked record' primary keyWhen you loop through a checkbox array, it only contains the rows which are checked and it is common practice to returns the record's primary key as the value of the checkbox(available as the the i'th array index as apex_application.g_f05(i) , where i is sequence position of the checked row) so that you can identify the record. -
SQL Query updateable report with row selector. Update process.
I have a SQL Query updateable report with the row selector(s).
How would I identify the row selector in an update process on the page.
I would like to update certain columns to a value of a select box on the page.
Using the basic:
UPDATE table_name
SET column1=value
WHERE some_column=some_value
I would need to do:
UPDATE table_name
SET column1= :P1_select
WHERE [row selector] = ?
Now sure how to identify the [row selector] and/or validate it is checked.
Thanks,
BobI don't have the apex_application.g_f01(i) referenced in the page source...In the page source you wouldn't find anything by that name
Identify the tabular form's checkbox column in the page(firebug/chrome developer panel makes this easy)
It should be like
<input id="..." value="" type="checkbox" name="fXX" >we are interested in the name attribute , get that number (between 01 and 50)
Replace that number in the code, for instance if it was f05 , the code would use
apex_application.g_f05
--i'th checked record' primary keyWhen you loop through a checkbox array, it only contains the rows which are checked and it is common practice to returns the record's primary key as the value of the checkbox(available as the the i'th array index as apex_application.g_f05(i) , where i is sequence position of the checked row) so that you can identify the record. -
Query to get the new customer or updated customer in last 3 days in AR
hi Consultants,
we have a custom customer summary table whcih maintain the all customer details with balance and aging bucket information.
we have program to update this custom table daily base based on the day transation. now we need to find the query to find new customer or updated customer in last 3 days.
then we need to update the customer to custom table .
Please advice me
Thanks in advance
Anu.Hi Vikram ,
Thanks for your reply.
Actually we have culoms in my custom table needs to update based on AR CUSTOMER
below culomn needs to update in my custom table .
CUSTOMER_ID
ADDRESS_ID
CUSTOMER_NUMBER
CUSTOMER_NAME
ADDRESS1
ADDRESS2
CITY
STATE
COUNTRY
PHONE_NUMBER
FAX_NUMBER
POSTAL_CODE
CONTACT_NAME
COLLECTOR_CODE
PAYMENT_TERMS
CREDIT_LIMIT
EXPIRATION_DATE
DB_RATING
DB_RISK_CLASS
DUNNING_LETTER_STAGE
LOCKBOX
ACCOUNT_OPENED
SALES_REP
LAST_COLL_CALL_COMMENT
FUTURE_ACTION_DATE
ORG_ID
LOCATION_NUMBER
HIGH_CREDIT_LIMIT_LAST_YEAR
HIGH_CREDIT_LIMIT_YTDPlease advice me how can we find the customer who update the above customer information in last 3 days.
Thanks,
Anu. -
How Can I Make This Sql Query To Load Data Correctly (sql server)?
Hi guys
I have a datagridview where the third column is a custom column with all days
of a month. It takes data with a query who distinct the column Improve.
Here is the code :
Private Sub fill_impro()
dgImprove.Rows.Clear()
Try
Dim i As Integer = 0
Dim query As String = "SELECT Improve,Price,Active,Idate FROM (SELECT Improve,Price,Active,Idate, ROW_NUMBER() OVER (PARTITION BY Price ORDER BY Price) AS rn FROM tblImprove) tmp WHERE rn = 1"
cmd = New SqlCommand(query, clsMSSQL.con)
myDR = cmd.ExecuteReader
If myDR.HasRows Then
While myDR.Read
dgImprove.Rows.Add()
dgImprove.Rows(i).Cells(0).Value = myDR.GetDecimal(myDR.GetOrdinal("Price"))
dgImprove.Rows(i).Cells(1).Value = myDR.GetString(myDR.GetOrdinal("Improve"))
Dim myday As Integer = DatePart(DateInterval.Day, myDR.GetValue(myDR.GetOrdinal("Idate")))
dgImprove.Rows(i).Cells(myday + 1).Value = myDR.GetInt32(myDR.GetOrdinal("Active"))
i = i + 1
End While
End If
myDR.Close()
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical, "Σφάλμα")
End Try
End Sub
And here is the result :
http://i60.tinypic.com/28gwf83.jpg
The column Active value is 1.
The problem is that column Active values are missing (red values in image).
How can i fix that ?
Thanks in advancetry like this
Dim Price As Decimal
Dim improve As String = String.Empty
While myDR.Read
Dim myday As Integer = DatePart(DateInterval.Day, myDR.GetValue(myDR.GetOrdinal("Idate")))
If Not (myDR.GetDecimal(myDR.GetOrdinal("Price")) = Price And myDR.GetString(myDR.GetOrdinal("Improve")) = improve) Then
i += 1
dgimprove.Rows.Add()
dgimprove.Rows(i).Cells(0).Value = myDR.GetDecimal(myDR.GetOrdinal("Price"))
dgimprove.Rows(i).Cells(1).Value = myDR.GetString(myDR.GetOrdinal("Improve"))
Price = myDR.GetDecimal(myDR.GetOrdinal("Price"))
improve = myDR.GetString(myDR.GetOrdinal("Improve"))
End If
dgimprove.Rows(i).Cells(myday + 1).Value = myDR.GetInt32(myDR.GetOrdinal("Active"))
End While
and change your sql statement to just
SELECT Improve,Price,Active,Idate FROM tblImprove WHERE Active = 1
Maybe you are looking for
-
Error in Creating New Web Application SharePoint 2013
Everything was working fine but today when i try to create a new web application i am getting the following error.It's happening whenever i am trying to create a new web application. The directory C:\inetpub\wwwroot\wss\VirtualDirectories\26060 is a
-
Hi I have the following menu item and the script to go with it. The itemCick event is not firing. <menuitem label="Blogs and News" selected="false" itemClick="itemClick(event);" /> <mx:Script> <![CDATA[ import mx.controls.Menu; import mx.events.MenuE
-
Accessing Pooled Virtual Desktops via RDP Client vs RDWeb
Hello, We have a Windows 2012 R2 Pooled Virtual Desktop PoC set up and can be accessed via RDWeb. We need to be able to access the pooled desktops via the RDP client. How can you specify the name of your Pooled Desktop Collection in the RDP client
-
Can I use Red Cam footage in FCE4
An actor friend of mine has shot a short film with a Red Cam and wants me to edit it. I assume I'll have to convert it, but can I bring that footage into FCE4, and if so what codec should I use? And how do I convert it, what program should be used.
-
Try to open .gz file...doesn't work
Try to open .gz file...doesn't work