SQL: Updating contents of a field by merging 2 fields together - sql-server

I wondered if anyone could help me with something I am having some issues with.
TB_SAMPLES contains a field called Notes. This field needs to be updated with the contents of my reference table, SUNCORE_NOTES_UPDATE. I need to add this new data as a prefix to any existing notes.
I have been able to select the values as I would like them to be displayed but I am not able to undertake the update. My 'select' code is below:
select traxx_supportb.[jlr_sql].[suncore_notes_update].notes + ' ' +
tb_samples_nw.notes as fullnotes
from tb_samples_nw, traxx_supportb.[jlr_sql].[suncore_notes_update]
where tb_samples_nw.id = traxx_supportb.[jlr_sql].[suncore_notes_update].id
Can anyone help me with the SQL required to add the contents to TB_SAMPLES.NOTES from SUNCORE_NOTES_UPDATE.NOTES as a prefix?
Thanks very much all!
J

UPDATE t1
SET notes = t2.notes + ' ' + t1.notes
FROM tb_samples_nw t1
JOIN traxx_supportb.[jlr_sql].[suncore_notes_update] t2
ON t1.id = t2.id

Try this:
update tb_samples_nw set notes = IsNull(suncore_notes_update.notes,'')+' '+IsNull(notes,'')
from traxx_supportb.[jlr_sql].[suncore_notes_update]
where tb_samples_nw.id = traxx_supportb.[jlr_sql].[suncore_notes_update].id

You can use an INNER JOIN with an UPDATE. It also makes it cleaner to alias the tables:
UPDATE s
SET s.notes = u.notes
+ ' '
+ s.notes
FROM tb_samples_nw s
INNER JOIN traxx_supportb.[jlr_sql].[suncore_notes_update] U
ON S.id = U.id
Be aware that the original note will be irreversibly modified, meaning that if you run the query again it will prepend the note again.

Related

SQL Duplicate column names error in Create View, even with aliases

The error is oddly specific, but I've just about honed in where it's occurring. The standard fix doesn't seem to be working though.
Here's where the error occurs. It's a big statement, so I'm just posting where I've found the error
CREATE OR REPLACE VIEW SalesInvoiceDoc
AS
( SELECT si.salinv_Num, si.salinv_Terms, si.salinv_SaleDate,
es.empName AS SalesAgent, man.empName AS ApprovingManager,
si.salinv_ApproveDate, ...
... FROM service_invoice si
JOIN employee es
ON (es.empID = si.salinv_EmpID)
JOIN employee man
ON (man.empID = si.salinv_ManID)
Essentially it's a Sales invoice document with a sales agent and approving manager. Both are stored in the employee table with a subtype discriminator set up for 'manager' or 'sales', and views for the subtype children tables to avoid duplication errors.
I've supplied aliases to try and avoid duplicate columns, but when I run this script, I get the duplicate column names error:
ORA-00957: duplicate column name
Does anyone know how to resolve this? Is it even possible? Any help would be greatly appreciated. Thank you in advance!
Edit: here's the full statement
CREATE OR REPLACE VIEW SalesInvoiceDoc
AS
( SELECT si.salinv_Num, si.salinv_Terms, si.salinv_SaleDate,
es.empName AS SalesAgent,
man.empName AS ApprovingManager, si.salinv_ApproveDate,
sc.custName, sc.custHouse, sc.custCity,
sc.custState, sc.custZIP, sc.custPhone, sc.custEmail,
sv.vehicle_VIN, sv.vehicle_year, sv.vehicle_make,
sv.vehicle_model, sv.vehicle_ext_color, sv.vehicle_trim,
sv.vehicle_list_base_price, sv.vehicle_mileage, sv.vehicle_condition,
sv.vehicle_description,
ti.vehicle_make, ti.vehicle_year, ti.vehicle_model, ti.vehicle_VIN,
ti.tradein_allowance,
sv.vehicle_list_base_price "SellingPrice", sv.shipping "Shipping",
ti.tradein_allowance "TradeAllowance",
(sv.vehicle_list_base_price + sv.shipping - ti.tradein_allowance) "Subtotal",
(sv.vehicle_list_base_price + sv.shipping - ti.tradein_allowance)*.0825 "Taxes",
(sv.vehicle_list_base_price + sv.shipping - ti.tradein_allowance)*1.0825 "TotalSellingPrice"
FROM sales_invoice si
JOIN employee es
ON (es.empID = si.salinv_EmpID)
JOIN employee man
ON (man.empID = si.salinv_ManID)
JOIN customer sc
ON (sc.custID = si.salinv_CustID)
JOIN vehicle sv
ON (sv.vehicle_VIN = si.salinv_SalVIN)
LEFT OUTER JOIN vehicle ti
ON (ti.vehicle_VIN = si.salinv_tiVIN)
);
You are duplicating column names from 2 different tables:
sv.vehicle_VIN,
sv.vehicle_year,
sv.vehicle_make,
sv.vehicle_model
and
ti.vehicle_make,
ti.vehicle_year,
ti.vehicle_model,
ti.vehicle_VIN
The resulting column name does not include the table alias.
Issue is cause sv.vehicle_VIN is appearing twice in your query and so does other columns. See below. You need to alias them all accordingly
**sv.vehicle_VIN**, **sv.vehicle_year**, **sv.vehicle_make**, **sv.vehicle_model**,
**ti.vehicle_make**, **ti.vehicle_year**, **ti.vehicle_model**, **ti.vehicle_VIN**,

How to avoid data repetition insertion?

Recently I have posted a question, it contains some syntax error, now the code is running without error, thanks to #Arulkumar.
But now I am facing one more problem, data from excel sheet is storing properly on to SQL Server database, but when I press refresh button or if I go to that link again in my application, data is repeating in the database. Means again it is retrieving values from excel and storing same data again in the database.
How can I avoid data repetition. Can any one please help me to solve this issue? Code and excel sheet sample is there in the above mentioned link.
You need MERGE statement
request.query('MERGE [mytable] as target USING (SELECT SalesPersonID, TerritoryID FROM OPENROWSET(' +
'\'Microsoft.ACE.OLEDB.12.0\', \'Excel 12.0;Database=D:\\sample\\test\\data\\1540_OPENROWSET_Examples.xls;HDR=YES\', ' +
'\'SELECT SalesPersonID, TerritoryID FROM [SELECT_Example$]\')' +
' ) as source' +
' ON target.SalesPersonID = source.SalesPersonID' +
' WHEN MATCHED THEN UPDATE SET TerritoryID = source.TerritoryID' +
' WHEN NOT MATCHED THEN INSERT (SalesPersonID, TerritoryID) VALUES (source.SalesPersonID, source.TerritoryID);'
,function(err,recordset){
if(err) console.log(err)
It will update TerritoryID if there is already row with same SalesPersonID and insert row if there is no matches in mytable.
If you need join on both fields change this:
ON target.SalesPersonID = source.SalesPersonID
On this:
ON target.SalesPersonID = source.SalesPersonID AND target.TerritoryID = source.TerritoryID
And after that - remove this string because it doesn't need anymore:
'WHEN MATCHED THEN UPDATE SET TerritoryID = source.TerritoryID' +

SQL - How can I return a value from a different table base on a parameter?

SQL - How can I return a value from a different table base on a parameter
First time poster, long time reader:
I am using a custom Excel function that allows be to pass parameters and build a SQL string that returns a value. This is working fine. However, I would like to choose among various tables based on the parameters that are passed.
At the moment I have two working functions with SQL statements look like this:
_______FUNCTION ONE________
<SQLText>
SELECT PRODDTA.TABLE1.T1DESC as DESCRIPTION
FROM PRODDTA.TABLE1
WHERE PRODDTA.TABLE1.T1KEY = '&PARM02'</SQLText>
_______FUNCTION TWO________
<SQLText>
SELECT PRODDTA.TABLE2.T2DESC as DESCRIPTION
FROM PRODDTA.TABLE2
WHERE PRODDTA.TABLE2.T2KEY = '&PARM02'</SQLText>
So I am using IF logic in Excel to check the first parameter and decide which function to use.
It would be much better if I could do a single SQL statement that could pick the right table based on the 1st parameter. Logically something like this:
_______FUNCTIONS COMBINED________
IF '&PARM02' = “A” THEN
SELECT PRODDTA.TABLE1.T1DESC as DESCRIPTION
FROM PRODDTA.TABLE1
WHERE PRODDTA.TABLE1.T1KEY = '&PARM02'
ELSE IF '&PARM02' = “B” THEN
SELECT PRODDTA.TABLE2.T2DESC as DESCRIPTION
FROM PRODDTA.TABLE2
WHERE PRODDTA.TABLE2.T2KEY = '&PARM02'
ELSE
DESCRIPTION = “”
Based on another post Querying different table based on a parameter I tried this exact syntax with no success
<SQLText>
IF'&PARM02'= "A"
BEGIN
SELECT PRODDTA.F0101.ABALPH as DESCRIPTION
FROM PRODDTA.F0101
WHERE PRODDTA.F0101.ABAN8 = '&PARM02'
END ELSE
BEGIN
SELECT PRODDTA.F4801.WADL01 as DESCRIPTION
FROM PRODDTA.F4801
WHERE PRODDTA.F4801.WADOCO = '&PARM02'
END</SQLText>
You could try using a JOIN statement.
http://www.sqlfiddle.com/#!9/23461d/1
Here is a fiddle showing two tables.
The following code snip will give you the values from both tables, using the Key as the matching logic.
SELECT Table1.description, Table1.key, Table2.description
from Table1
Join Table2 on Table1.key = Table2.key
Here's one way to do it. If PARM03='Use Table1' then the top half of the union will return records and vice versa. This won't necessarily product good performance though. You should consider why you are storing data in this way. It looks like you are partitioning data across different tables which is a bad idea.
SELECT PRODDTA.TABLE1.T1DESC as DESCRIPTION
FROM PRODDTA.TABLE1
WHERE PRODDTA.TABLE1.T1KEY = '&PARM02'
AND &PARM03='Use Table1'
UNION ALL
SELECT PRODDTA.TABLE2.T2DESC as DESCRIPTION
FROM PRODDTA.TABLE2
WHERE PRODDTA.TABLE2.T2KEY = '&PARM02'</SQLText>
AND &PARM03='Use Table2'

Trouble with query in vb.net

I'm getting an error stating that say column doesnt belong to table. Here is my query below, its pretty straight forward.
query = " SELECT A.COLUMN "
" FROM TABLE_1 A, TABLE_2 B"
" WHERE A.COLUMN = B.COLUMN "
For simplicity sake, I put it into a dataset and do a for loop and it works fine. By the way tested query in management studio and it all works fine.
This is where have the problem:
dim new_val as string
new_val = row("A.COLUMN") 'ERROR
NOTE: When i change my query to :
SELECT A.COLUMN **AS COLUMN1**
and then:
new_val = row("COLUMN1") it works.
Does anyone know the reason for this?? Also forgot to note that some columns have the same name thats why i use A.COLUMN.
Just use:
new_val = row("COLUMN")
There is no reason to have the table suffix in your reference, just the column name.
Also, you really should re-write your query to use INNER JOINS:
query = " SELECT A.COLUMN "
" FROM TABLE_1 A INNER JOIN TABLE_2 B ON A.COLUMN = B.COLUMN "
I would suggest that you set the breakpoint in the problematic line and check the name of the column in the quick watch window. In this case, you will be able to determine the column name and thus adjust your code.

Update on linked server with nested subquery

I want to update on a linked server the result of a query as well from a linked server.
The first sql snippet gives me the value to be updated:
SELECT mmdb_vessel.IMONo, mmdb_vessel.DeathDate
From OPENQUERY(MMDB, 'SELECT FunctionalLocation, IMONo, VesselStatus, CONVERT(VARCHAR(10), DeathDate, 102) AS DeathDate
FROM VESSEL
WHERE VESSEL.VesselStatusID <> 42 AND VESSEL.DeathDate is not null') as mmdb_vessel
, eb_all_v
WHERE
eb_all_v.IMO_No = mmdb_vessel.IMONo
AND eb_all_v.status = 'in service'
the second is actually what I'm not able to implement, it should show what I want to achieve:
UPDATE EPI2..EPI.PLANT
SET KIND_OF_LIQUIDATION_NO = 1
, LIQUIDATION_DATE = [result from snippet above].DeathDate
Where EPI2..EPI.PLANT.IMONo = [result from snippet above].IMONo
I'm not so sure if my explanation is sufficient, please feel free to ask for additional information!
Thanks, already in advance,
Werner
I would recommend to select the data from the remote server first and store the required data e.g. in a temptable, because LinkedServer and updates can have some sideeffects (e.g. performing a tablescan on the remote table, altough you would not expect it if an updaet is involved, etc) - but this depends on your exact usage/scenario.
Select data you need to update
SELECT * INTO #tmpTable FROM LINKEDSERVER.EPI.dbo.PLANT WHERE ....
Perform the update on local server
UPDATE EPI2..EPI.PLANT SET KIND_OF_LIQUIDATION_NO = 1, LIQUIDATION_DATE = t.DeathDate FROM #tmpTable t INNER JOIN EPI2..EPI.PLANT p on t.IMONo = p.IMONo

Resources